summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--c++.html.markdown18
-rw-r--r--dart.html.markdown2
-rw-r--r--edn.html.markdown16
-rw-r--r--elixir.html.markdown2
-rw-r--r--es-es/brainfuck-es.html.markdown18
-rw-r--r--es-es/git-es.html.markdown14
-rw-r--r--es-es/javascript-es.html.markdown20
-rw-r--r--es-es/json-es.html.markdown16
-rw-r--r--es-es/swift-es.html.markdown596
-rw-r--r--fr-fr/HTML-fr.html.markdown115
-rw-r--r--fr-fr/css-fr.html.markdown8
-rw-r--r--fr-fr/d.html.markdown264
-rw-r--r--fr-fr/markdown.html.markdown2
-rw-r--r--fr-fr/perl-fr.html.markdown174
-rw-r--r--fsharp.html.markdown6
-rw-r--r--javascript.html.markdown7
-rw-r--r--julia.html.markdown16
-rw-r--r--markdown.html.markdown235
-rw-r--r--matlab.html.markdown1
-rw-r--r--objective-c.html.markdown13
-rw-r--r--perl6.html.markdown29
-rw-r--r--python.html.markdown4
-rw-r--r--python3.html.markdown2
-rw-r--r--ruby.html.markdown5
-rw-r--r--swift.html.markdown5
-rw-r--r--uk-ua/javascript-ua.html.markdown (renamed from ua-ua/javascript-ua.html.markdown)0
-rw-r--r--visualbasic.html.markdown126
-rw-r--r--whip.html.markdown8
-rw-r--r--yaml.html.markdown31
-rw-r--r--zh-cn/swift-cn.html.markdown131
30 files changed, 1589 insertions, 295 deletions
diff --git a/c++.html.markdown b/c++.html.markdown
index d03092e5..6b452b1b 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -801,6 +801,24 @@ void doSomethingWithAFile(const std::string& filename)
// all automatically destroy their contents when they fall out of scope.
// - Mutexes using lock_guard and unique_lock
+// containers with object keys of non-primitive values (custom classes) require
+// compare function in the object itself or as a function pointer. Primitives
+// have default comparators, but you can override it.
+class Foo {
+public:
+ int j;
+ Foo(int a) : j(a) {}
+};
+struct compareFunction {
+ bool operator()(const Foo& a, const Foo& b) const {
+ return a.j < b.j;
+ }
+};
+//this isn't allowed (although it can vary depending on compiler)
+//std::map<Foo, int> fooMap;
+std::map<Foo, int, compareFunction> fooMap;
+fooMap[Foo(1)] = 1;
+fooMap.find(Foo(1)); //true
/////////////////////
// Fun stuff
diff --git a/dart.html.markdown b/dart.html.markdown
index f7601271..fc7b220e 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -498,7 +498,7 @@ main() {
## Further Reading
-Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a
+Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
useful Try Dart online.
http://www.dartlang.org/
http://try.dartlang.org/
diff --git a/edn.html.markdown b/edn.html.markdown
index 0a0dc9b5..d0bdddfc 100644
--- a/edn.html.markdown
+++ b/edn.html.markdown
@@ -5,13 +5,13 @@ contributors:
- ["Jason Yeo", "https://github.com/jsyeo"]
---
-Extensible Data Notation or EDN for short is a format for serializing data.
+Extensible Data Notation (EDN) is a format for serializing data.
-The notation is used internally by Clojure to represent programs and it also
+The notation is used internally by Clojure to represent programs. It is also
used as a data transfer format like JSON. Though it is more commonly used in
-Clojure land, there are implementations of EDN for many other languages.
+Clojure, there are implementations of EDN for many other languages.
-The main benefit of EDN over JSON and YAML is that it is extensible, which we
+The main benefit of EDN over JSON and YAML is that it is extensible. We
will see how it is extended later on.
```Clojure
@@ -59,7 +59,7 @@ false
; Vectors allow random access
[:gelato 1 2 -2]
-; Maps are associative data structures that associates the key with its value
+; Maps are associative data structures that associate the key with its value
{:eggs 2
:lemon-juice 3.5
:butter 1}
@@ -68,7 +68,7 @@ false
{[1 2 3 4] "tell the people what she wore",
[5 6 7 8] "the more you see the more you hate"}
-; You may use commas for readability. They are treated as whitespaces.
+; You may use commas for readability. They are treated as whitespace.
; Sets are collections that contain unique elements.
#{:a :b 88 "huat"}
@@ -82,11 +82,11 @@ false
#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}
; Let me explain this with a clojure example. Suppose I want to transform that
-; piece of edn into a MenuItem record.
+; piece of EDN into a MenuItem record.
(defrecord MenuItem [name rating])
-; To transform edn to clojure values, I will need to use the built in EDN
+; To transform EDN to clojure values, I will need to use the built in EDN
; reader, edn/read-string
(edn/read-string "{:eggs 2 :butter 1 :flour 5}")
diff --git a/elixir.html.markdown b/elixir.html.markdown
index eedeb227..720e080c 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -343,6 +343,7 @@ rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
+#=> "rescued a runtime error"
# All exceptions have a message
try do
@@ -351,6 +352,7 @@ rescue
x in [RuntimeError] ->
x.message
end
+#=> "some error"
## ---------------------------
## -- Concurrency
diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown
index e33d672d..550511da 100644
--- a/es-es/brainfuck-es.html.markdown
+++ b/es-es/brainfuck-es.html.markdown
@@ -9,8 +9,10 @@ lang: es-es
---
Brainfuck (con mayúscula sólo al inicio de una oración) es un
-lenguaje de programación mínimo, computacionalmente universal
-en tamaño con sólo 8 comandos.
+lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos.
+
+Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/).
+
```
@@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas)
será ignorado.
Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
-en cero y un apuntador en la celda actual.
+en cero y un puntero apuntando la celda actual.
Existen ocho comandos:
@@ -26,7 +28,7 @@ Existen ocho comandos:
- : Decrementa 1 al valor de la celda actual.
> : Mueve el apuntador a la siguiente celda. (a la derecha)
< : Mueve el apuntador a la celda anterior. (a la izquierda)
-. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A')
+. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A')
, : Lee un caracter como input y lo escribe en la celda actual.
[ : Si el valor en la celda actual es cero mueve el apuntador
hasta el primer ']' que encuentre. Si no es cero sigue a la
@@ -37,7 +39,7 @@ Existen ocho comandos:
[ y ] forman un while. Obviamente, deben estar balanceados.
-Ahora unos ejemplos de programas escritos con brainfuck.
+Estos son algunos ejemplos de programas escritos con brainfuck.
++++++ [ > ++++++++++ < - ] > +++++ .
@@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un
cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
-Ten en mente que los espacios son sólo para fines de legibilidad.
+Ten en cuenta que los espacios son sólo para fines de legibilidad.
Es lo mismo escribir el ejemplo de arriba que esto:
,[>+<-]>.
@@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la
celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
el resultado.
```
-Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir
+Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir
tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
intérprete es relativamente sencillo de hacer, pero si eres masoquista,
-intenta construir tu proprio intérprete de brainfuck... en brainfuck.
+puedes intentar construir tu propio intérprete de brainfuck... en brainfuck.
diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown
index 18b544b4..4e1e68ba 100644
--- a/es-es/git-es.html.markdown
+++ b/es-es/git-es.html.markdown
@@ -18,11 +18,11 @@ versionar y administrar nuestro código fuente.
## Versionamiento, conceptos.
-### Qué es el control de versiones?
+### ¿Qué es el control de versiones?
El control de versiones es un sistema que guarda todos los cambios realizados en
uno o varios archivos, a lo largo del tiempo.
-### Versionamiento centralizado vs Versionamiento Distribuido.
+### Versionamiento centralizado vs versionamiento distribuido.
+ El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar
archivos.
@@ -33,9 +33,9 @@ uno o varios archivos, a lo largo del tiempo.
[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones)
-### Por qué usar Git?
+### ¿Por qué usar Git?
-* Se puede trabajar sin conexion.
+* Se puede trabajar sin conexión.
* ¡Colaborar con otros es sencillo!.
* Derivar, crear ramas del proyecto (aka: Branching) es fácil.
* Combinar (aka: Merging)
@@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo.
### Repositorio
Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka:
-comits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
+commits), y encabezados (aka: heads). Imagina que un repositorio es una clase,
y que sus atributos otorgan acceso al historial del elemento, además de otras
cosas.
@@ -62,12 +62,12 @@ y mas.
### Directorio de trabajo (componentes del repositorio)
-Es basicamente los directorios y archivos dentro del repositorio. La mayoría de
+Es básicamente los directorios y archivos dentro del repositorio. La mayoría de
las veces se le llama "directorio de trabajo".
### Índice (componentes del directorio .git)
-El índice es el área de inicio en git. Es basicamente la capa que separa el
+El índice es el área de inicio en git. Es básicamente la capa que separa el
directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores
más poder sobre lo que se envía y se recibe del repositorio.
diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index d475cf42..9ef0c63e 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -30,7 +30,7 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto
// Cada sentencia puede ser terminada con punto y coma ;
hazAlgo();
-// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente
+// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente
// cada que se detecta una nueva línea, a excepción de algunos casos.
hazAlgo()
@@ -109,7 +109,7 @@ null == undefined; // = true
null === undefined; // false
// Los Strings funcionan como arreglos de caracteres
-// Puedes accesar a cada caracter con la función charAt()
+// Puedes acceder a cada caracter con la función charAt()
"Este es un String".charAt(0); // = 'E'
// ...o puedes usar la función substring() para acceder a pedazos más grandes
@@ -186,7 +186,7 @@ miObjeto.miLlave; // = "miValor"
// agregar nuevas llaves.
miObjeto.miTerceraLlave = true;
-// Si intentas accesar con una llave que aún no está asignada tendrás undefined.
+// Si intentas acceder con una llave que aún no está asignada tendrás undefined.
miObjeto.miCuartaLlave; // = undefined
///////////////////////////////////
@@ -301,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per
//inmediatamente", que preveé variables temporales de fugarse al ámbito global
(function(){
var temporal = 5;
- // Podemos accesar al ámbito global asignando al 'objeto global', el cual
+ // Podemos acceder al ámbito global asignando al 'objeto global', el cual
// en un navegador siempre es 'window'. El objeto global puede tener
// un nombre diferente en ambientes distintos, por ejemplo Node.js .
window.permanente = 10;
@@ -321,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){
alert(texto);
}
setTimeout(interna, 5000);
- // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos
+ // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos
// terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos
// Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene
// acceso a la variable 'texto' cuando es llamada.
@@ -339,7 +339,7 @@ var miObjeto = {
};
miObjeto.miFuncion(); // = "¡Hola Mundo!"
-// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables
+// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables
// del objeto con la palabra clave 'this'.
miObjeto = {
miString: "¡Hola Mundo!",
@@ -401,11 +401,11 @@ var MiConstructor = function(){
miNuevoObjeto = new MiConstructor(); // = {miNumero: 5}
miNuevoObjeto.miNumero; // = 5
-// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una
+// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una
// propiedad en un objeto que no existe en el objeto el intérprete buscará en
// el prototipo.
-// Algunas implementaciones de JavaScript te permiten accesar al prototipo de
+// Algunas implementaciones de JavaScript te permiten acceder al prototipo de
// un objeto con la propiedad __proto__. Mientras que esto es útil para explicar
// prototipos, no es parte del estándar; veremos formas estándar de usar prototipos
// más adelante.
@@ -440,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43;
miObjeto.sentidoDeLaVida; // = 43
// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no
-// existe una forma estándar de accesar al prototipo de un objeto. De todas formas.
+// existe una forma estándar de acceder al prototipo de un objeto. De todas formas.
// hay dos formas de crear un nuevo objeto con un prototipo dado.
// El primer método es Object.create, el cual es una adición reciente a JavaScript,
@@ -476,7 +476,7 @@ typeof miNumero; // = 'number'
typeof miNumeroObjeto; // = 'object'
miNumero === miNumeroObjeyo; // = false
if (0){
- // Este código no se ejecutara porque 0 es false.
+ // Este código no se ejecutará porque 0 es false.
}
// Aún así, los objetos que envuelven y los prototipos por defecto comparten
diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown
index fff678eb..c98049f9 100644
--- a/es-es/json-es.html.markdown
+++ b/es-es/json-es.html.markdown
@@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
"llaves": "siempre debe estar entre comillas (ya sean dobles o simples)",
"numeros": 0,
"strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".",
- "soporta booleanos?": true,
- "vacios": null,
+ "¿soporta booleanos?": true,
+ "vacíos": null,
"numero grande": 1.2e+100,
"objetos": {
- "comentario": "La mayoria de tu estructura vendra de objetos.",
+ "comentario": "La mayoría de tu estructura vendrá de objetos.",
"arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5],
"otro objeto": {
- "comentario": "Estas cosas pueden estar anidadas, muy util."
+ "comentario": "Estas cosas pueden estar anidadas, muy útil."
}
},
- "tonteria": [
+ "tontería": [
{
"fuentes de potasio": ["bananas"]
},
@@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead
"estilo alternativo": {
"comentario": "Mira esto!"
- , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido"
- , "otro comentario": "que lindo"
+ , "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido"
+ , "otro comentario": "qué lindo"
},
- "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer."
+ "eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer."
}
```
diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown
new file mode 100644
index 00000000..c04ab02b
--- /dev/null
+++ b/es-es/swift-es.html.markdown
@@ -0,0 +1,596 @@
+---
+language: swift
+contributors:
+ - ["Grant Timmerman", "http://github.com/grant"]
+ - ["Christopher Bess", "http://github.com/cbess"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Anthony Nguyen", "http://github.com/anthonyn60"]
+translators:
+ - ["David Hsieh", "http://github.com/deivuh"]
+lang: es-es
+filename: learnswift-es.swift
+---
+
+Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado
+por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra
+el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia
+de desarrolladores de Apple.
+
+Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), el cual tiene un completo tutorial de Swift.
+
+
+```swift
+// Importar un módulo
+import UIKit
+
+//
+// MARK: Básicos
+//
+
+// XCode soporta referencias para anotar tu código y agregarlos a lista de la
+// barra de saltos.
+// MARK: Marca de sección
+// TODO: Hacer algo pronto
+// FIXME: Arreglar este código
+
+// En Swift 2, println y print fueron combinados en un solo método print.
+// Print añade una nueva línea automáticamente.
+print("Hola, mundo") // println ahora es print
+print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea
+
+// Valores de variables (var) pueden cambiar después de ser asignados
+// Valores de constrantes (let) no pueden cambiarse después de ser asignados
+
+var myVariable = 42
+let øπΩ = "value" // nombres de variable unicode
+let π = 3.1415926
+let convenience = "keyword" // nombre de variable contextual
+// Las declaraciones pueden ser separadas por punto y coma (;)
+let weak = "keyword"; let override = "another keyword"
+// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de
+// variable
+let `class` = "keyword"
+let explicitDouble: Double = 70
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Conversión (casting)
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string
+
+// Valores específicos de la compilación (build)
+// utiliza la configuración -D
+#if false
+ print("No impreso")
+ let buildValue = 3
+#else
+ let buildValue = 7
+#endif
+print("Build value: \(buildValue)") // Build value: 7
+
+/*
+ Las opcionales son un aspecto del lenguaje Swift que permite el
+ almacenamiento de un valor `Some` (algo) o `None` (nada).
+
+ Debido a que Swift requiere que cada propiedad tenga un valor,
+ hasta un valor 'nil' debe de ser explicitamente almacenado como un
+ valor opcional.
+
+ Optional<T> es un enum.
+*/
+var someOptionalString: String? = "opcional" // Puede ser nil
+// Al igual que lo anterior, pero ? es un operador postfix (sufijo)
+var someOptionalString2: Optional<String> = "opcional"
+
+if someOptionalString != nil {
+ // No soy nil
+ if someOptionalString!.hasPrefix("opt") {
+ print("Tiene el prefijo")
+ }
+
+ let empty = someOptionalString?.isEmpty
+}
+someOptionalString = nil
+
+// Opcional implícitamente desenvuelto
+var unwrappedString: String! = "Un valor esperado."
+// Al igual que lo anterior, pero ! es un operador postfix (sufijo)
+var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Un valor esperado."
+
+if let someOptionalStringConstant = someOptionalString {
+ // tiene valor `Some` (algo), no nil
+ if !someOptionalStringConstant.hasPrefix("ok") {
+ // No tiene el prefijo
+ }
+}
+
+// Swift tiene soporte de almacenamiento para cualquier tipo de valor.
+// AnyObject == id
+// A diferencia de Objective-C `id`, AnyObject funciona con cualquier
+// valor (Class, Int, struct, etc)
+var anyObjectVar: AnyObject = 7
+anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible."
+
+/*
+ Comentar aquí
+
+ /*
+ Comentarios anidados también son soportados
+ */
+*/
+
+//
+// MARK: Colecciones
+//
+
+/*
+ Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras).
+ Así que `let` y `var` también indican si son mudables (var) o
+ inmutables (let) durante la declaración de sus tipos.
+*/
+
+// Array (arreglo)
+var shoppingList = ["catfish", "water", "lemons"]
+shoppingList[1] = "bottle of water"
+let emptyArray = [String]() // let == inmutable
+let emptyArray2 = Array<String>() // igual que lo anterior
+var emptyMutableArray = [String]() // var == mudable
+
+
+// Dictionary (diccionario)
+var occupations = [
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
+]
+occupations["Jayne"] = "Public Relations"
+let emptyDictionary = [String: Float]() // let == inmutable
+let emptyDictionary2 = Dictionary<String, Float>() // igual que lo anterior
+var emptyMutableDictionary = [String: Float]() // var == mudable
+
+
+//
+// MARK: Flujo de control
+//
+
+// Ciclo for (array)
+let myArray = [1, 1, 2, 3, 5]
+for value in myArray {
+ if value == 1 {
+ print("Uno!")
+ } else {
+ print("No es uno!")
+ }
+}
+
+// Ciclo for (dictionary)
+var dict = ["uno": 1, "dos": 2]
+for (key, value) in dict {
+ print("\(key): \(value)")
+}
+
+// Ciclo for (range)
+for i in -1...shoppingList.count {
+ print(i)
+}
+shoppingList[1...2] = ["steak", "peacons"]
+// Utilizar ..< para excluir el último valor
+
+// Ciclo while
+var i = 1
+while i < 1000 {
+ i *= 2
+}
+
+// Ciclo do-while
+do {
+ print("Hola")
+} while 1 == 2
+
+// Switch
+// Muy potente, se puede pensar como declaraciones `if` con _azúcar sintáctico_
+// Soportan String, instancias de objetos, y primitivos (Int, Double, etc)
+let vegetable = "red pepper"
+switch vegetable {
+case "celery":
+ let vegetableComment = "Add some raisins and make ants on a log."
+case "cucumber", "watercress":
+ let vegetableComment = "That would make a good tea sandwich."
+case let localScopeValue where localScopeValue.hasSuffix("pepper"):
+ let vegetableComment = "Is it a spicy \(localScopeValue)?"
+default: // obligatorio (se debe cumplir con todos los posibles valores de entrada)
+ let vegetableComment = "Everything tastes good in soup."
+}
+
+
+//
+// MARK: Funciones
+//
+
+// Funciones son un tipo de primera-clase, quiere decir que pueden ser anidados
+// en funciones y pueden ser pasados como parámetros
+
+// Función en documentación de cabeceras Swift (formato reStructedText)
+
+/**
+ Una operación de saludo
+
+ - Una viñeta en la documentación
+ - Otra viñeta en la documentación
+
+ :param: name Un nombre
+ :param: day Un día
+ :returns: Un string que contiene el valor de name y day
+*/
+func greet(name: String, day: String) -> String {
+ return "Hola \(name), hoy es \(day)."
+}
+greet("Bob", "Martes")
+
+// Similar a lo anterior, a excepción del compartamiento de los parámetros
+// de la función
+func greet2(requiredName: String, externalParamName localParamName: String) -> String {
+ return "Hola \(requiredName), hoy es el día \(localParamName)"
+}
+greet2(requiredName:"John", externalParamName: "Domingo")
+
+// Función que devuelve múltiples valores en una tupla
+func getGasPrices() -> (Double, Double, Double) {
+ return (3.59, 3.69, 3.79)
+}
+let pricesTuple = getGasPrices()
+let price = pricesTuple.2 // 3.79
+// Ignorar tupla (u otros) valores utilizando _ (guión bajo)
+let (_, price1, _) = pricesTuple // price1 == 3.69
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
+
+// Cantidad variable de argumentos
+func setup(numbers: Int...) {
+ // Es un arreglo
+ let number = numbers[0]
+ let argCount = numbers.count
+}
+
+// Pasando y devolviendo funciones
+func makeIncrementer() -> (Int -> Int) {
+ func addOne(number: Int) -> Int {
+ return 1 + number
+ }
+ return addOne
+}
+var increment = makeIncrementer()
+increment(7)
+
+// Pasando como referencia
+func swapTwoInts(inout a: Int, inout b: Int) {
+ let tempA = a
+ a = b
+ b = tempA
+}
+var someIntA = 7
+var someIntB = 3
+swapTwoInts(&someIntA, &someIntB)
+print(someIntB) // 7
+
+
+//
+// MARK: Closures (Clausuras)
+//
+var numbers = [1, 2, 6]
+
+// Las funciones son un caso especial de closure ({})
+
+// Ejemplo de closure.
+// `->` Separa los argumentos del tipo de retorno
+// `in` Separa la cabecera del cuerpo del closure
+numbers.map({
+ (number: Int) -> Int in
+ let result = 3 * number
+ return result
+})
+
+// Cuando se conoce el tipo, como en lo anterior, se puede hacer esto
+numbers = numbers.map({ number in 3 * number })
+// o esto
+//numbers = numbers.map({ $0 * 3 })
+
+print(numbers) // [3, 6, 18]
+
+// Closure restante
+numbers = sorted(numbers) { $0 > $1 }
+
+print(numbers) // [18, 6, 3]
+
+// Bastante corto, debido a que el operador < infiere los tipos
+
+numbers = sorted(numbers, < )
+
+print(numbers) // [3, 6, 18]
+
+//
+// MARK: Estructuras
+//
+
+// Las estructuras y las clases tienen capacidades similares
+struct NamesTable {
+ let names = [String]()
+
+ // Subscript personalizado
+ subscript(index: Int) -> String {
+ return names[index]
+ }
+}
+
+// Las estructuras tienen un inicializador designado autogenerado (implícitamente)
+let namesTable = NamesTable(names: ["Me", "Them"])
+let name = namesTable[1]
+print("Name is \(name)") // Name is Them
+
+//
+// MARK: Clases
+//
+
+// Las clases, las estructuras y sus miembros tienen tres niveles de control de acceso
+// Éstos son: internal (predeterminado), public, private
+
+public class Shape {
+ public func getArea() -> Int {
+ return 0;
+ }
+}
+
+// Todos los métodos y las propiedades de una clase son public (públicas)
+// Si solo necesitas almacenar datos en un objecto estructurado,
+// debes de utilizar `struct`
+
+internal class Rect: Shape {
+ var sideLength: Int = 1
+
+ // Getter y setter personalizado
+ private var perimeter: Int {
+ get {
+ return 4 * sideLength
+ }
+ set {
+ // `newValue` es una variable implícita disponible para los setters
+ sideLength = newValue / 4
+ }
+ }
+
+ // Lazily loading (inicialización bajo demanda) a una propiedad
+ // subShape queda como nil (sin inicializar) hasta que getter es llamado
+ lazy var subShape = Rect(sideLength: 4)
+
+ // Si no necesitas un getter y setter personalizado
+ // pero aún quieres ejecutar código antes y después de hacer get o set
+ // a una propiedad, puedes utilizar `willSet` y `didSet`
+ var identifier: String = "defaultID" {
+ // El argumento `willSet` será el nombre de variable para el nuevo valor
+ willSet(someIdentifier) {
+ print(someIdentifier)
+ }
+ }
+
+ init(sideLength: Int) {
+ self.sideLength = sideLength
+ // Siempre poner super.init de último al momento de inicializar propiedades
+ // personalizadas
+ super.init()
+ }
+
+ func shrink() {
+ if sideLength > 0 {
+ --sideLength
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
+ }
+}
+
+// Una clase simple `Square` que extiende de `Rect`
+class Square: Rect {
+ convenience init() {
+ self.init(sideLength: 5)
+ }
+}
+
+var mySquare = Square()
+print(mySquare.getArea()) // 25
+mySquare.shrink()
+print(mySquare.sideLength) // 4
+
+// Conversión de tipo de instancia
+let aShape = mySquare as Shape
+
+// Comparar instancias, no es igual a == que compara objetos (equal to)
+if mySquare === mySquare {
+ print("Yep, it's mySquare")
+}
+
+// Inicialización (init) opcional
+class Circle: Shape {
+ var radius: Int
+ override func getArea() -> Int {
+ return 3 * radius * radius
+ }
+
+ // Un signo de interrogación como sufijo después de `init` es un init opcional
+ // que puede devolver nil
+ init?(radius: Int) {
+ self.radius = radius
+ super.init()
+
+ if radius <= 0 {
+ return nil
+ }
+ }
+}
+
+var myCircle = Circle(radius: 1)
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
+var myEmptyCircle = Circle(radius: -1)
+print(myEmptyCircle?.getArea()) // "nil"
+if let circle = myEmptyCircle {
+ // no será ejecutado debido a que myEmptyCircle es nil
+ print("circle is not nil")
+}
+
+
+//
+// MARK: Enums
+//
+
+
+// Los enums pueden ser opcionalmente de un tipo específico o de su propio tipo
+// Al igual que las clases, pueden contener métodos
+
+enum Suit {
+ case Spades, Hearts, Diamonds, Clubs
+ func getIcon() -> String {
+ switch self {
+ case .Spades: return "♤"
+ case .Hearts: return "♡"
+ case .Diamonds: return "♢"
+ case .Clubs: return "♧"
+ }
+ }
+}
+
+// Los valores de enum permite la sintaxis corta, sin necesidad de poner
+// el tipo del enum cuando la variable es declarada de manera explícita
+var suitValue: Suit = .Hearts
+
+// Enums de tipo no-entero requiere asignaciones de valores crudas directas
+enum BookName: String {
+ case John = "John"
+ case Luke = "Luke"
+}
+print("Name: \(BookName.John.rawValue)")
+
+// Enum con valores asociados
+enum Furniture {
+ // Asociación con Int
+ case Desk(height: Int)
+ // Asociación con String e Int
+ case Chair(String, Int)
+
+ func description() -> String {
+ switch self {
+ case .Desk(let height):
+ return "Desk with \(height) cm"
+ case .Chair(let brand, let height):
+ return "Chair of \(brand) with \(height) cm"
+ }
+ }
+}
+
+var desk: Furniture = .Desk(height: 80)
+print(desk.description()) // "Desk with 80 cm"
+var chair = Furniture.Chair("Foo", 40)
+print(chair.description()) // "Chair of Foo with 40 cm"
+
+
+//
+// MARK: Protocolos
+//
+
+// `protocol` puede requerir que los tipos tengan propiedades
+// de instancia específicas, métodos de instancia, métodos de tipo,
+// operadores, y subscripts
+
+
+protocol ShapeGenerator {
+ var enabled: Bool { get set }
+ func buildShape() -> Shape
+}
+
+// Protocolos declarados con @objc permiten funciones opcionales,
+// que te permite evaluar conformidad
+@objc protocol TransformShape {
+ optional func reshaped()
+ optional func canReshape() -> Bool
+}
+
+class MyShape: Rect {
+ var delegate: TransformShape?
+
+ func grow() {
+ sideLength += 2
+
+ // Pon un signo de interrogación después de la propiedad opcional,
+ // método, o subscript para ignorar un valor nil y devolver nil
+ // en lugar de tirar un error de tiempo de ejecución
+ // ("optional chaining")
+ if let allow = self.delegate?.canReshape?() {
+ // test for delegate then for method
+ self.delegate?.reshaped?()
+ }
+ }
+}
+
+
+//
+// MARK: Otros
+//
+
+// `extension`: Agrega funcionalidades a tipos existentes
+
+// Square ahora se "conforma" al protocolo `Printable`
+extension Square: Printable {
+ var description: String {
+ return "Area: \(self.getArea()) - ID: \(self.identifier)"
+ }
+}
+
+print("Square: \(mySquare)")
+
+// También puedes hacer extend a tipos prefabricados (built-in)
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
+
+// Generics: Similar Java y C#. Utiliza la palabra clave `where` para
+// especificar los requerimientos de los genéricos.
+
+func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in enumerate(array) {
+ if value == valueToFind {
+ return index
+ }
+ }
+ return nil
+}
+let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+print(foundAtIndex == 2) // true
+
+// Operadores:
+// Operadores personalizados puede empezar con los siguientes caracteres:
+// / = - + * % < > ! & | ^ . ~
+// o
+// Caracteres unicode: math, symbol, arrow, dingbat, y line/box.
+prefix operator !!! {}
+
+// Un operador prefix que triplica la longitud del lado cuando es utilizado
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+// Valor actual
+print(mySquare.sideLength) // 4
+
+// Cambiar la longitud del lado utilizando el operador !!!,
+// incrementa el tamaño por 3
+!!!mySquare
+print(mySquare.sideLength) // 12
+```
diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown
new file mode 100644
index 00000000..fdde9107
--- /dev/null
+++ b/fr-fr/HTML-fr.html.markdown
@@ -0,0 +1,115 @@
+---
+language: html
+filename: learnhtml-fr.html
+contributors:
+ - ["Christophe THOMAS", "https://github.com/WinChris"]
+lang: fr-fr
+---
+HTML signifie HyperText Markup Language.
+C'est un langage (format de fichiers) qui permet d'écrire des pages internet.
+C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais).
+Les fichiers HTML sont en réalité de simple fichier texte.
+Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante.
+Ce balisage sert à donner une signification au texte ainsi entouré.
+Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5.
+
+**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
+Cet article porte principalement sur la syntaxe et quelques astuces.
+
+
+```HTML
+<!-- Les commentaires sont entouré comme cette ligne! -->
+
+<!-- #################### Les balises #################### -->
+
+<!-- Voici un exemple de fichier HTML que nous allons analyser -->
+<!-- Venez voir ce que ça donne -->
+
+<!doctype html>
+ <html>
+ <head>
+ <title>Mon Site</title>
+ </head>
+ <body>
+ <h1>Hello, world!</h1>
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a>
+ <p>Ceci est un paragraphe</p>
+ <p>Ceci est un autre paragraphe</p>
+ <ul>
+ <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
+ <li>Ceci est un autre item</li>
+ <li>Et ceci est le dernier item de la liste</li>
+ </ul>
+ </body>
+ </html>
+
+<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML -->
+
+<!doctype html>
+
+<!-- Après ça on commence par ouvrir une balise <html> -->
+<html>
+</html>
+<!-- Et puis on la referme à la fin du fichier avec </html> -->
+<!-- après cette balise de fin, plus rien ne doit apparaître. -->
+
+<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : -->
+
+<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) -->
+<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées -->
+
+<head>
+ <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre -->
+</head>
+
+<!-- Après la balise <head>, on trouve la balise <body> -->
+<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. -->
+<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu -->
+
+<body>
+ <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre -->
+ <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) -->
+ <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" -->
+ <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html -->
+ <p>Ceci est un autre paragraphe</p>
+ <ul> <!-- La balise <ul> permet d'introduire une liste à puces -->
+ <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc -->
+ <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li>
+ <li>Ceci est un autre item</li>
+ <li>Et ceci est le dernier item de la liste</li>
+ </ul>
+</body>
+
+<!-- Voilà comment créer un fichier HTML simple -->
+
+<!-- Mais il est possible d'ajouter encore des balises plus spécifiques -->
+
+<!-- Pour insérer une image -->
+<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" -->
+<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur -->
+
+<!-- Il est possible de réaliser des tableaux également -->
+
+<table> <!-- On ouvre la balise <table> -->
+ <tr> <!-- <tr> permet de créer une ligne -->
+ <th>First Header</th> <!-- <th> permet de créer un titre au tableau -->
+ <th>Second Header</th>
+ </tr>
+ <tr>
+ <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule -->
+ <td>Première ligne, deuxième cellule</td>
+ </tr>
+ <tr>
+ <td>Deuxième ligne, première cellule</td>
+ <td>Deuxième ligne, deuxième cellule</td>
+ </tr>
+</table>
+
+## Utilisation
+
+Le HTML s'écrit dans des fichiers `.html`.
+
+## En savoir plus
+
+* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html)
+* [W3School](http://www.w3schools.com/html/html_intro.asp)
diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown
index bdab9715..35673c47 100644
--- a/fr-fr/css-fr.html.markdown
+++ b/fr-fr/css-fr.html.markdown
@@ -8,7 +8,7 @@ translators:
lang: fr-fr
---
-Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs,
+Au début du web, il n'y avait pas d'élements visuels, simplement du texte pur. Mais avec le dévelopement des navigateurs,
des pages avec du contenu visuel sont arrivées.
CSS est le langage standard qui existe et permet de garder une séparation entre
le contenu (HTML) et le style d'une page web.
@@ -16,8 +16,8 @@ le contenu (HTML) et le style d'une page web.
En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents
sur une page HTML afin de leur donner des propriétés visuelles différentes.
-Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0
-qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur.
+Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parler de CSS2.0
+qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateurs.
**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
Cet article porte principalement sur la syntaxe et quelques astuces.
@@ -33,7 +33,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces.
/* Généralement, la première déclaration en CSS est très simple */
selecteur { propriete: valeur; /* autres proprietés...*/ }
-/* Le sélécteur sert à cibler un élément du HTML
+/* Le sélecteur sert à cibler un élément du HTML
Vous pouvez cibler tous les éléments d'une page! */
* { color:red; }
diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown
new file mode 100644
index 00000000..d9bd9b48
--- /dev/null
+++ b/fr-fr/d.html.markdown
@@ -0,0 +1,264 @@
+---
+language: D
+filename: learnd-fr.d
+contributors:
+ - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"]
+translators:
+ - ["Quentin Ladeveze", "aceawan.eu"]
+lang: fr-fr
+---
+
+```d
+// Commençons par un classique
+module hello;
+
+import std.stdio;
+
+// args n'est pas obligatoire
+void main(string[] args) {
+ writeln("Bonjour le monde !");
+}
+```
+
+Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a
+de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/).
+D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient
+des fonctionnalités aussi bien de bas niveau que de haut niveau.
+
+D est activement développé par de nombreuses personnes très intelligents, guidées par
+[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et
+[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu).
+Après cette petite introduction, jetons un coup d'oeil à quelques exemples.
+
+```d
+import std.stdio;
+
+void main() {
+ //Les conditions et les boucles sont classiques.
+ for(int i = 0; i < 10000; i++) {
+ writeln(i);
+ }
+
+ // On peut utiliser auto pour inférer automatiquement le
+ // type d'une variable.
+ auto n = 1;
+
+ // On peut faciliter la lecture des valeurs numériques
+ // en y insérant des `_`.
+ while(n < 10_000) {
+ n += n;
+ }
+
+ do {
+ n -= (n / 2);
+ } while(n > 0);
+
+ // For et while sont très utiles, mais en D, on préfère foreach.
+ // Les deux points : '..', créent un intervalle continue de valeurs
+ // incluant la première mais excluant la dernière.
+ foreach(i; 1..1_000_000) {
+ if(n % 2 == 0)
+ writeln(i);
+ }
+
+ // On peut également utiliser foreach_reverse pour itérer à l'envers.
+ foreach_reverse(i; 1..int.max) {
+ if(n % 2 == 1) {
+ writeln(i);
+ } else {
+ writeln("Non !");
+ }
+ }
+}
+```
+On peut définir de nouveaux types avec les mots-clés `struct`, `class`,
+`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés)
+De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques.
+
+```d
+// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java.
+struct LinkedList(T) {
+ T data = null;
+
+ // Utilisez '!' pour instancier un type paramétré.
+ // Encore une fois semblable à '<T>'
+ LinkedList!(T)* next;
+}
+
+class BinTree(T) {
+ T data = null;
+
+ // Si il n'y a qu'un seul paramètre de template,
+ // on peut s'abstenir de mettre des parenthèses.
+ BinTree!T left;
+ BinTree!T right;
+}
+
+enum Day {
+ Sunday,
+ Monday,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+}
+
+// Utilisez alias pour créer des abreviations pour les types.
+alias IntList = LinkedList!int;
+alias NumTree = BinTree!double;
+
+// On peut tout aussi bien créer des templates de function !
+T max(T)(T a, T b) {
+ if(a < b)
+ return b;
+
+ return a;
+}
+
+// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé
+// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur.
+// Ici ils seront toujours passés par référence à 'swap()'.
+void swap(T)(ref T a, ref T b) {
+ auto temp = a;
+
+ a = b;
+ b = temp;
+}
+
+// Avec les templates, on peut également passer des valeurs en paramètres.
+class Matrix(uint m, uint n, T = int) {
+ T[m] rows;
+ T[n] columns;
+}
+
+auto mat = new Matrix!(3, 3); // T est 'int' par défaut
+
+```
+À propos de classes, parlons des propriétés. Une propriété est, en gros,
+une méthode qui peut se comporter comme une lvalue. On peut donc utiliser
+la syntaxe des structures classiques (`struct.x = 7`) comme si il
+s'agissait de méthodes getter ou setter.
+
+```d
+// Considérons une classe paramétrée avec les types 'T' et 'U'
+class MyClass(T, U) {
+ T _data;
+ U _other;
+}
+
+// Et des méthodes "getter" et "setter" comme suit:
+class MyClass(T, U) {
+ T _data;
+ U _other;
+
+ // Les constructeurs s'apellent toujours 'this'.
+ this(T t, U u) {
+ // Ceci va appeller les setters ci-dessous.
+ data = t;
+ other = u;
+ }
+
+ // getters
+ @property T data() {
+ return _data;
+ }
+
+ @property U other() {
+ return _other;
+ }
+
+ // setters
+ @property void data(T t) {
+ _data = t;
+ }
+
+ @property void other(U u) {
+ _other = u;
+ }
+}
+
+// Et on l'utilise de cette façon:
+void main() {
+ auto mc = new MyClass!(int, string)(7, "seven");
+
+ // Importer le module 'stdio' de la bibliothèque standard permet
+ // d'écrire dans la console (les imports peuvent être locaux à une portée)
+ import std.stdio;
+
+ // On appelle les getters pour obtenir les valeurs.
+ writefln("Earlier: data = %d, str = %s", mc.data, mc.other);
+
+ // On appelle les setter pour assigner de nouvelles valeurs.
+ mc.data = 8;
+ mc.other = "eight";
+
+ // On appelle les setter pour obtenir les nouvelles valeurs.
+ writefln("Later: data = %d, str = %s", mc.data, mc.other);
+}
+```
+Avec les propriétés, on peut constuire nos setters et nos getters
+comme on le souhaite, tout en gardant un syntaxe très propre,
+comme si on accédait directement à des membres de la classe.
+
+Les autres fonctionnalités orientées objets à notre disposition
+incluent les interfaces, les classes abstraites, et la surcharge
+de méthodes. D gère l'héritage comme Java: On ne peut hériter que
+d'une seule classe et implémenter autant d'interface que voulu.
+
+Nous venons d'explorer les fonctionnalités objet du D, mais changeons
+un peu de domaine. D permet la programmation fonctionelle, avec les fonctions
+de premier ordre, les fonctions `pure` et les données immuables.
+De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter)
+sont disponibles dans le module `std.algorithm`.
+
+```d
+import std.algorithm : map, filter, reduce;
+import std.range : iota; // construit un intervalle excluant la dernière valeur.
+
+void main() {
+ // On veut un algorithm qui affiche la somme de la listes des carrés
+ // des entiers paires de 1 à 100. Un jeu d'enfant !
+
+ // On se content de passer des expressions lambda en paramètre à des templates.
+ // On peut fournier au template n'importe quelle fonction, mais dans notre
+ // cas, les lambdas sont pratiques.
+ auto num = iota(1, 101).filter!(x => x % 2 == 0)
+ .map!(y => y ^^ 2)
+ .reduce!((a, b) => a + b);
+
+ writeln(num);
+}
+```
+
+Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ?
+C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax".
+Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière
+classique, ou comme un appelle à une méthode. Walter Brighter a écrit un
+article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394)
+Pour faire court, on peut appeller une fonction dont le premier paramètre
+est de type A, comme si c'était une méthode de A.
+
+J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça
+Voyons comment on le fait en D !
+
+```d
+import std.stdio;
+import std.parallelism : parallel;
+import std.math : sqrt;
+
+void main() {
+ // On veut calculer la racine carré de tous les nombres
+ // dans notre tableau, et profiter de tous les coeurs
+ // à notre disposition.
+ auto arr = new double[1_000_000];
+
+ // On utilise un index et une référence à chaque élément du tableau.
+ // On appelle juste la fonction parallel sur notre tableau !
+ foreach(i, ref elem; parallel(arr)) {
+ ref = sqrt(i + 1.0);
+ }
+}
+
+
+```
diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown
index e5e7c73a..66f0efbe 100644
--- a/fr-fr/markdown.html.markdown
+++ b/fr-fr/markdown.html.markdown
@@ -2,7 +2,7 @@
language: markdown
contributors:
- ["Andrei Curelaru", "http://www.infinidad.fr"]
-filename: markdown.md
+filename: markdown-fr.md
lang: fr-fr
---
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
new file mode 100644
index 00000000..e737b7aa
--- /dev/null
+++ b/fr-fr/perl-fr.html.markdown
@@ -0,0 +1,174 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl-fr.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
+translators:
+ - ["Matteo Taroli", "http://www.matteotaroli.be"]
+lang: fr-fr
+---
+Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
+
+Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
+est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
+
+```perl
+# Les commentaires en une ligne commencent par un dièse
+
+
+#### Types de variables de Perl
+
+# Les variables comment par un symbole précisant le type.
+# Un nom de variable valide commence par une lettre ou un underscore,
+# suivi d'un nombre quelconque de lettres, chiffres ou underscores.
+
+### Perl a trois types principaux de variables: $scalaire, @tableau and %hash
+
+## Scalaires
+# Un scalaire représente une valeur unique :
+my $animal = "chameau";
+my $reponse = 42;
+
+# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante
+# et Perl les convertira automatiquement entre elles quand nécessaire.
+
+## Tableaux
+# Un tableau représente une liste de valeurs :
+my @animaux = ("chameau", "lama", "chouette");
+my @nombres = (23, 42, 69);
+my @melange = ("chameau", 42, 1.23);
+
+## Hashes
+# Un hash représente un ensemble de paires de clé/valeur :
+my %fruit_couleur = ("pomme", "rouge", "banane", "jaune");
+
+# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment :
+
+my %fruit_couleur = (
+ pomme => "rouge",
+ banane => "jaune"
+);
+
+# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata
+# (perldoc perldata)
+
+# Des types de données plus complexes peuvent être construits en utilisant des références,
+# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes.
+
+#### Conditions et boucles
+
+# Perl possède la plupart des conditions et boucles habituelles.
+
+if ($var) {
+ ...
+} elsif ($var eq 'bar') {
+ ...
+} else {
+ ...
+}
+
+unless (condition) {
+ ...
+}
+# Ceci est fourni en tant que version plus lisible de "if (!condition)"
+
+# la postcondition à la sauce Perl
+
+print "Yow!" if $zippy;
+print "Nous n'avons pas de banane." unless $bananes;
+
+# while
+while (condition) {
+ ...
+}
+
+# boucle for et iteration
+for (my $i = 0; $i < $max; $i++) {
+ print "l'index est $i";
+}
+
+for (my $i = 0; $i < @elements; $i++) {
+ print "L'élément courant est " . $elements[$i];
+}
+
+for my $element (@elements) {
+ print $element;
+}
+
+# implicitement
+
+# La variable de contexte scalaire $_ est utilisée par défaut dans différentes
+# situations, comme par exemple dans la boucle foreach ou en argument par défaut
+# de la plupart des fonctions pour en simplifier l'écriture.
+
+# Dans l'exemple suivant, $_ prends successivement la valeur de
+# chaque élément de la liste.
+
+for (@elements) {
+ print; # affiche le contenu de $_
+}
+
+
+#### Expressions régulières
+
+# Le support des expressions régulières par Perl est aussi large que profond
+# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs.
+# Cependant, pour faire court :
+
+# Simple correspondance
+if (/foo/) { ... } # vrai si $_ contient "foo"
+if ($a =~ /foo/) { ... } # vrai si $a contient "foo"
+
+# Simple substitution
+
+$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a
+$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a
+
+
+#### Fichiers et E/S
+
+# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()".
+
+open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!";
+open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!";
+open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!";
+
+# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>".
+# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier
+# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un
+# élément de la liste :
+
+my $ligne = <$in>
+my $lignes = <$in>
+
+#### Ecrire des fonctions
+
+# Ecrire des fonctions est facile :
+
+sub logger {
+ my $logmessage = shift;
+
+ open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!";
+
+ print $logfile $logmessage;
+}
+
+# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée :
+
+logger("On a une fonction de logging!!");
+```
+
+#### Utiliser des modules Perl
+
+Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl.
+
+Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser.
+
+#### Pour en savoir plus
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Learn at www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - and perl built-in : `perldoc perlintro`
diff --git a/fsharp.html.markdown b/fsharp.html.markdown
index d63b9f1d..809a1da2 100644
--- a/fsharp.html.markdown
+++ b/fsharp.html.markdown
@@ -335,10 +335,10 @@ module DataTypeExamples =
let worker = Worker jdoe
// ------------------------------------
- // Modelling with types
+ // Modeling with types
// ------------------------------------
- // Union types are great for modelling state without using flags
+ // Union types are great for modeling state without using flags
type EmailAddress =
| ValidEmailAddress of string
| InvalidEmailAddress of string
@@ -526,7 +526,7 @@ module AsyncExample =
|> Async.RunSynchronously // start them off
// ================================================
-// .NET compatability
+// .NET compatibility
// ================================================
module NetCompatibilityExamples =
diff --git a/javascript.html.markdown b/javascript.html.markdown
index e285ca4e..98261334 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -561,7 +561,9 @@ of the language.
[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal
-[Javascript: The Right Way][9] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
+[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples.
+
+[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
In addition to direct contributors to this article, some content is adapted from
@@ -577,4 +579,5 @@ Mozilla Developer Network.
[6]: http://www.amazon.com/gp/product/0596805527/
[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
[8]: http://eloquentjavascript.net/
-[9]: http://jstherightway.org/
+[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
+[10]: http://jstherightway.org/
diff --git a/julia.html.markdown b/julia.html.markdown
index cba7cd45..ef3ea244 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -2,6 +2,7 @@
language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
+ - ["Pranit Bauva", "http://github.com/pranitbauva1997"]
filename: learnjulia.jl
---
@@ -102,6 +103,11 @@ false
# Printing is easy
println("I'm Julia. Nice to meet you!")
+# String can be compared lexicographically
+"good" > "bye" # => true
+"good" == "good" # => true
+"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true
+
####################################################
## 2. Variables and Collections
####################################################
@@ -390,6 +396,14 @@ end
add(5, 6) # => 11 after printing out "x is 5 and y is 6"
+# Compact assignment of functions
+f_add(x, y) = x + y # => "f (generic function with 1 method)"
+f_add(3, 4) # => 7
+
+# Function can also return multiple values as tuple
+f(x, y) = x + y, x - y
+f(3, 4) # => (7, -1)
+
# You can define functions that take a variable number of
# positional arguments
function varargs(args...)
@@ -723,7 +737,7 @@ code_native(square_area, (Float64,))
# ret
#
# Note that julia will use floating point instructions if any of the
-# arguements are floats.
+# arguments are floats.
# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
circle_area(5) # 78.53981633974483
diff --git a/markdown.html.markdown b/markdown.html.markdown
index b956a5f2..8961c995 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -2,45 +2,63 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
filename: markdown.md
---
-Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
-
-Give me as much feedback as you want! / Feel free to fork and pull request!
+Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
+Markdown also varies in implementation from one parser to a next. This
+guide will attempt to clarify when features are universal or when they are
+specific to a certain parser.
+
+- [HTML Elements](#html-elements)
+- [Headings](#headings)
+- [Simple Text Styles](#simple-text-styles)
+- [Paragraphs](#paragraphs)
+- [Lists](#lists)
+- [Code blocks](#code-blocks)
+- [Horizontal rule](#horizontal-rule)
+- [Links](#links)
+- [Images](#images)
+- [Miscellany](#miscellany)
+
+## HTML Elements
+Markdown is a superset of HTML, so any HTML file is valid Markdown.
```markdown
-<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown. This
-means we can use HTML elements in Markdown, such as the comment element, and
-they won't be affected by a markdown parser. However, if you create an HTML
-element in your markdown file, you cannot use markdown syntax within that
-element's contents. -->
+<!--This means we can use HTML elements in Markdown, such as the comment element,
+and they won't be affected by a markdown parser. However, if you create an HTML element
+in your markdown file, you cannot use markdown syntax within that element's contents.-->
+```
-<!-- Markdown also varies in implementation from one parser to a next. This
-guide will attempt to clarify when features are universal or when they are
-specific to a certain parser. -->
+## Headings
-<!-- Headings -->
-<!-- You can create HTML elements <h1> through <h6> easily by prepending the
-text you want to be in that element by a number of hashes (#). -->
+You can create HTML elements `<h1>` through `<h6>` easily by prepending the
+text you want to be in that element by a number of hashes (#).
+
+```markdown
# This is an <h1>
## This is an <h2>
### This is an <h3>
#### This is an <h4>
##### This is an <h5>
###### This is an <h6>
+```
+Markdown also provides us with two alternative ways of indicating h1 and h2.
-<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. -->
+```markdown
This is an h1
=============
This is an h2
-------------
+```
+## Simple text styles
-<!-- Simple text styles -->
-<!-- Text can be easily styled as italic or bold using markdown. -->
+Text can be easily styled as italic or bold using markdown.
+```markdown
*This text is in italics.*
_And so is this text._
@@ -50,15 +68,20 @@ __And so is this text.__
***This text is in both.***
**_As is this!_**
*__And this!__*
+```
-<!-- In Github Flavored Markdown, which is used to render markdown files on
-Github, we also have strikethrough: -->
+In Github Flavored Markdown, which is used to render markdown files on
+Github, we also have strikethrough:
+```markdown
~~This text is rendered with strikethrough.~~
+```
+## Paragraphs
-<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or
-multiple blank lines. -->
+Paragraphs are a one or multiple adjacent lines of text separated by one or
+multiple blank lines.
+```markdown
This is a paragraph. I'm typing in a paragraph isn't this fun?
Now I'm in paragraph 2.
@@ -66,16 +89,20 @@ I'm still in paragraph 2 too!
I'm in paragraph three!
+```
-<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
-with two or more spaces and then begin a new paragraph. -->
+Should you ever want to insert an HTML <br /> tag, you can end a paragraph
+with two or more spaces and then begin a new paragraph.
+```markdown
I end with two spaces (highlight me to see them).
There's a <br /> above me!
+```
-<!-- Block quotes are easy and done with the > character. -->
+Block quotes are easy and done with the > character.
+```markdown
> This is a block quote. You can either
> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own.
> It doesn't make a difference so long as they start with a `>`.
@@ -84,9 +111,12 @@ There's a <br /> above me!
>> of indentation?
> How neat is that?
-<!-- Lists -->
-<!-- Unordered lists can be made using asterisks, pluses, or hyphens. -->
+```
+
+## Lists
+Unordered lists can be made using asterisks, pluses, or hyphens.
+```markdown
* Item
* Item
* Another item
@@ -102,159 +132,182 @@ or
- Item
- Item
- One last item
+```
+Ordered lists are done with a number followed by a period.
-<!-- Ordered lists are done with a number followed by a period. -->
-
+```markdown
1. Item one
2. Item two
3. Item three
+```
-<!-- You don't even have to label the items correctly and markdown will still
-render the numbers in order, but this may not be a good idea. -->
+You don't even have to label the items correctly and markdown will still
+render the numbers in order, but this may not be a good idea.
+```markdown
1. Item one
1. Item two
1. Item three
-<!-- (This renders the same as the above example) -->
-
-<!-- You can also use sublists. -->
+```
+(This renders the same as the above example)
+You can also use sublists
+```markdown
1. Item one
2. Item two
3. Item three
* Sub-item
* Sub-item
4. Item four
+```
-<!-- There are even task lists. This creates HTML checkboxes. -->
+There are even task lists. This creates HTML checkboxes.
+```markdown
Boxes below without the 'x' are unchecked HTML checkboxes.
- [ ] First task to complete.
- [ ] Second task that needs done
This checkbox below will be a checked HTML checkbox.
- [x] This task has been completed
+```
+
+## Code blocks
-<!-- Code blocks -->
-<!-- You can indicate a code block (which uses the <code> element) by indenting
-a line with four spaces or a tab. -->
+You can indicate a code block (which uses the `<code>` element) by indenting
+a line with four spaces or a tab.
+```markdown
This is code
So is this
+```
-<!-- You can also re-tab (or add an additional four spaces) for indentation
-inside your code. -->
+You can also re-tab (or add an additional four spaces) for indentation
+inside your code
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Inline code can be created using the backtick character ` -->
+Inline code can be created using the backtick character `
+```markdown
John didn't even know what the `go_to()` function did!
+```
-<!-- In Github Flavored Markdown, you can use a special syntax for code. -->
-
+In Github Flavored Markdown, you can use a special syntax for code
+```markdown
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
def foobar
puts "Hello world!"
end
\`\`\` <!-- here too, no backslashes, just ``` -->
+```
-<!-- The above text doesn't require indenting, plus Github will use syntax
-highlighting of the language you specify after the ``` -->
+The above text doesn't require indenting, plus Github will use syntax
+highlighting of the language you specify after the \`\`\`
-<!-- Horizontal rule (<hr />) -->
-<!-- Horizontal rules are easily added with three or more asterisks or hyphens,
-with or without spaces. -->
+## Horizontal rule
+Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
+with or without spaces.
+```markdown
***
---
- - -
****************
+```
-<!-- Links -->
-<!-- One of the best things about markdown is how easy it is to make links. Put
-the text to display in hard brackets [] followed by the url in parentheses (). -->
+## Links
-[Click me!](http://test.com/)
-
-<!-- You can also add a link title using quotes inside the parentheses. -->
+One of the best things about markdown is how easy it is to make links. Put
+the text to display in hard brackets [] followed by the url in parentheses ()
+```markdown
+[Click me!](http://test.com/)
+```
+You can also add a link title using quotes inside the parentheses.
+```markdown
[Click me!](http://test.com/ "Link to Test.com")
-
-<!-- Relative paths work too. -->
-
+```
+Relative paths work too.
+```markdown
[Go to music](/music/).
-
-<!-- Markdown also supports reference style links. -->
-
+```
+Markdown also supports reference style links.
+```markdown
[Click this link][link1] for more info about it!
[Also check out this link][foobar] if you want to.
[link1]: http://test.com/ "Cool!"
[foobar]: http://foobar.biz/ "Alright!"
-
-<!-- The title can also be in single quotes or in parentheses, or omitted
+```
+The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
-can be anything so long as they are unique. -->
-
-<!-- There is also "implicit naming" which lets you use the link text as the id. -->
+can be anything so long as they are unique.
+There is also "implicit naming" which lets you use the link text as the id.
+```markdown
[This][] is a link.
[this]: http://thisisalink.com/
+```
+But it's not that commonly used.
-<!-- But it's not that commonly used. -->
-
-<!-- Images -->
-<!-- Images are done the same way as links but with an exclamation point in front! -->
-
+## Images
+Images are done the same way as links but with an exclamation point in front!
+```markdown
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
-
-<!-- And reference style works as expected. -->
-
+```
+And reference style works as expected.
+```markdown
![This is the alt-attribute.][myimage]
[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
+```
-<!-- Miscellany -->
-<!-- Auto-links -->
-
+## Miscellany
+### Auto-links
+```markdown
<http://testwebsite.com/> is equivalent to
[http://testwebsite.com/](http://testwebsite.com/)
+```
-<!-- Auto-links for emails -->
-
+### Auto-links for emails
+```markdown
<foo@bar.com>
+```
-<!-- Escaping characters -->
-
+### Escaping characters
+```markdown
I want to type *this text surrounded by asterisks* but I don't want it to be
in italics, so I do this: \*this text surrounded by asterisks\*.
+```
-<!-- Keyboard keys -->
-<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys. -->
+### Keyboard keys
+In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
+```markdown
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
+### Tables
-<!-- Tables -->
-<!-- Tables are only available in Github Flavored Markdown and are slightly
-cumbersome, but if you really want it: -->
-
+Tables are only available in Github Flavored Markdown and are slightly
+cumbersome, but if you really want it:
+```markdown
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
| Left-aligned | Centered | Right-aligned |
| blah | blah | blah |
+```
+or, for the same results
-<!-- or, for the same results -->
-
+```markdown
Col 1 | Col2 | Col3
:-- | :-: | --:
Ugh this is so ugly | make it | stop
-
-<!-- The end! -->
-
```
-
+---
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 9d78978e..25f762bb 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -15,6 +15,7 @@ If you have any feedback please feel free to reach me at
[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com).
```matlab
+%% Code sections start with two percent signs. Section titles go on the same line.
% Comments start with a percent sign.
%{
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 1fa731e3..097cb846 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -1,13 +1,12 @@
---
-
language: Objective-C
contributors:
- ["Eugene Yagrushkin", "www.about.me/yagrushkin"]
- ["Yannick Loriot", "https://github.com/YannickL"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: LearnObjectiveC.m
-
---
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
@@ -152,13 +151,13 @@ int main (int argc, const char * argv[])
[mutableDictionary setObject:@"value1" forKey:@"key1"];
[mutableDictionary setObject:@"value2" forKey:@"key2"];
[mutableDictionary removeObjectForKey:@"key1"];
-
+
// Change types from Mutable To Immutable
//In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];
-
-
+
+
// Set object
NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order)
@@ -605,7 +604,7 @@ int main (int argc, const char * argv[]) {
// Starting in Xcode 7.0, you can create Generic classes,
// allowing you to provide greater type safety and clarity
-// without writing excessive boilerplate.
+// without writing excessive boilerplate.
@interface Result<__covariant A> : NSObject
- (void)handleSuccess:(void(^)(A))success
@@ -633,7 +632,7 @@ Result<NSArray *> *result;
@property (nonatomic) NSNumber * object;
@end
-// It should be obvious, however, that writing one
+// It should be obvious, however, that writing one
// Class to solve a problem is always preferable to writing two
// Note that Clang will not accept generic types in @implementations,
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 45b15f05..3eec19f3 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1,10 +1,9 @@
---
-name: perl6
category: language
language: perl6
filename: learnperl6.pl
contributors:
- - ["Nami-Doc", "http://github.com/Nami-Doc"]
+ - ["vendethiel", "http://github.com/vendethiel"]
---
Perl 6 is a highly capable, feature-rich programming language made for at
@@ -374,6 +373,8 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return
say join(' ', @array[15..*]); #=> 15 16 17 18 19
# which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
+# Note: if you try to do either of those with an infinite loop,
+# you'll trigger an infinite loop (your program won't finish)
# You can use that in most places you'd expect, even assigning to an array
my @numbers = ^20;
@@ -763,8 +764,9 @@ try {
# and `enum`) are actually packages. (Packages are the lowest common denominator)
# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
-# You usually don't use packages directly: you use `class Package::Name::Here;`,
-# or if you only want to export variables/subs, you can use `module`:
+# You're not supposed to use the package keyword, usually:
+# you use `class Package::Name::Here;` to declare a class,
+# or if you only want to export variables/subs, you can use `module`:
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
# that can be redeclared as something else later.
@@ -774,11 +776,6 @@ unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
-# NOTE for Perl 5 users: even though the `package` keyword exists,
-# the braceless form is invalid (to catch a "perl5ism"). This will error out:
-# package Foo; # because Perl 6 will think the entire file is Perl 5
-# Just use `module` or the brace version of `package`.
-
# You can use a module (bring its declarations into scope) with `use`
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; #=> [1]
@@ -870,8 +867,16 @@ LEAVE { say "Runs everytime you leave a block, even when an exception
PRE { say "Asserts a precondition at every block entry,
before ENTER (especially useful for loops)" }
+# exemple:
+for 0..2 {
+ PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
+}
+
POST { say "Asserts a postcondition at every block exit,
after LEAVE (especially useful for loops)" }
+for 0..2 {
+ POST { $_ < 2 } # This is going to blow up with "Postcondition failed"
+}
## * Block/exceptions phasers
sub {
@@ -1239,14 +1244,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left
# Group: you can group parts of your regexp with `[]`.
# These groups are *not* captured (like PCRE's `(?:)`).
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
-so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
+so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
# The previous line returns `True`.
-# We match the "ABC" 1 or more time (the `+` was applied to the group).
+# We match the "012" 1 or more time (the `+` was applied to the group).
# But this does not go far enough, because we can't actually get back what
# we matched.
# Capture: We can actually *capture* the results of the regexp, using parentheses.
-so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below)
+so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)
# So, starting with the grouping explanations.
# As we said before, our `Match` object is available as `$/`:
diff --git a/python.html.markdown b/python.html.markdown
index 2b43c5fc..f8f712d3 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -458,7 +458,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
-# positional args, which will be interpreted as a tuple if you do not use the *
+# positional args, which will be interpreted as a tuple by using *
def varargs(*args):
return args
@@ -466,7 +466,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
-# keyword args, as well, which will be interpreted as a dict if you do not use **
+# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
return kwargs
diff --git a/python3.html.markdown b/python3.html.markdown
index 2398e7ac..1f9d0e42 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -689,7 +689,7 @@ i.age # => raises an AttributeError
# You can import modules
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# You can get specific functions from a module
from math import ceil, floor
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 8720fec6..243f788b 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -14,6 +14,7 @@ contributors:
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gabriel Halley", "https://github.com/ghalley"]
- ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
---
```ruby
@@ -53,7 +54,7 @@ You shouldn't either
10.* 5 #=> 50
# Special values are objects
-nil # Nothing to see here
+nil # equivalent to null in other languages
true # truth
false # falsehood
@@ -131,7 +132,7 @@ puts "I'm printing!"
# print to the output without a newline
print "I'm printing!"
-#=> I'm printing! => nill
+#=> I'm printing! => nil
# Variables
x = 25 #=> 25
diff --git a/swift.html.markdown b/swift.html.markdown
index 1ca81bc2..f3746613 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Joey Huang", "http://github.com/kamidox"]
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
- ["Clayton Walker", "https://github.com/cwalk"]
+ - ["Fernando Valverde", "http://visualcosita.xyz"]
filename: learnswift.swift
---
@@ -25,7 +26,7 @@ import UIKit
// Xcode supports landmarks to annotate your code and lists them in the jump bar
// MARK: Section mark
-// MARK: - Section mark with a separator line
+// MARK: - Section mark with a separator line
// TODO: Do something soon
// FIXME: Fix this code
@@ -83,7 +84,7 @@ if someOptionalString != nil {
someOptionalString = nil
/*
- Trying to use ! to access a non-existent optional value triggers a runtime
+ Trying to use ! to access a non-existent optional value triggers a runtime
error. Always make sure that an optional contains a non-nil value before
using ! to force-unwrap its value.
*/
diff --git a/ua-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown
index fedbf5ac..fedbf5ac 100644
--- a/ua-ua/javascript-ua.html.markdown
+++ b/uk-ua/javascript-ua.html.markdown
diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown
index accdbf56..0371e6f6 100644
--- a/visualbasic.html.markdown
+++ b/visualbasic.html.markdown
@@ -9,13 +9,13 @@ filename: learnvisualbasic.vb
Module Module1
Sub Main()
- ' A Quick Overview of Visual Basic Console Applications before we dive
- ' in to the deep end.
- ' Apostrophe starts comments.
- ' To Navigate this tutorial within the Visual Basic Complier, I've put
- ' together a navigation system.
- ' This navigation system is explained however as we go deeper into this
- ' tutorial, you'll understand what it all means.
+ 'A Quick Overview of Visual Basic Console Applications before we dive
+ 'in to the deep end.
+ 'Apostrophe starts comments.
+ 'To Navigate this tutorial within the Visual Basic Complier, I've put
+ 'together a navigation system.
+ 'This navigation system is explained however as we go deeper into this
+ 'tutorial, you'll understand what it all means.
Console.Title = ("Learn X in Y Minutes")
Console.WriteLine("NAVIGATION") 'Display
Console.WriteLine("")
@@ -32,9 +32,9 @@ Module Module1
Console.WriteLine("50. About")
Console.WriteLine("Please Choose A Number From The Above List")
Dim selection As String = Console.ReadLine
- ' The "Case" in the Select statement is optional.
- ' For example, "Select selection" instead of "Select Case selection"
- ' will also work.
+ 'The "Case" in the Select statement is optional.
+ 'For example, "Select selection" instead of "Select Case selection"
+ 'will also work.
Select Case selection
Case "1" 'HelloWorld Output
Console.Clear() 'Clears the application and opens the private sub
@@ -45,10 +45,10 @@ Module Module1
Case "3" 'Calculating Whole Numbers
Console.Clear()
CalculatingWholeNumbers()
- Case "4" 'Calculting Decimal Numbers
+ Case "4" 'Calculating Decimal Numbers
Console.Clear()
CalculatingDecimalNumbers()
- Case "5" 'Working Calcculator
+ Case "5" 'Working Calculator
Console.Clear()
WorkingCalculator()
Case "6" 'Using Do While Loops
@@ -77,10 +77,10 @@ Module Module1
'One - I'm using numbers to help with the above navigation when I come back
'later to build it.
- 'We use private subs to seperate different sections of the program.
+ 'We use private subs to separate different sections of the program.
Private Sub HelloWorldOutput()
'Title of Console Application
- Console.Title = "Hello World Ouput | Learn X in Y Minutes"
+ Console.Title = "Hello World Output | Learn X in Y Minutes"
'Use Console.Write("") or Console.WriteLine("") to print outputs.
'Followed by Console.Read() alternatively Console.Readline()
'Console.ReadLine() prints the output to the console.
@@ -91,18 +91,18 @@ Module Module1
'Two
Private Sub HelloWorldInput()
Console.Title = "Hello World YourName | Learn X in Y Minutes"
- ' Variables
- ' Data entered by a user needs to be stored.
- ' Variables also start with a Dim and end with an As VariableType.
+ 'Variables
+ 'Data entered by a user needs to be stored.
+ 'Variables also start with a Dim and end with an As VariableType.
- ' In this tutorial, we want to know what your name, and make the program
- ' respond to what is said.
+ 'In this tutorial, we want to know what your name, and make the program
+ 'respond to what is said.
Dim username As String
'We use string as string is a text based variable.
Console.WriteLine("Hello, What is your name? ") 'Ask the user their name.
username = Console.ReadLine() 'Stores the users name.
Console.WriteLine("Hello " + username) 'Output is Hello 'Their name'
- Console.ReadLine() 'Outsputs the above.
+ Console.ReadLine() 'Outputs the above.
'The above will ask you a question followed by printing your answer.
'Other variables include Integer and we use Integer for whole numbers.
End Sub
@@ -110,7 +110,7 @@ Module Module1
'Three
Private Sub CalculatingWholeNumbers()
Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes"
- Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect
+ Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104, etc
Dim a As Integer = Console.ReadLine()
Console.Write("Second number: ") 'Enter second whole number.
Dim b As Integer = Console.ReadLine()
@@ -126,10 +126,10 @@ Module Module1
'Of course we would like to be able to add up decimals.
'Therefore we could change the above from Integer to Double.
- 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect
+ 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9, etc
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
- Console.Write("Second number: ") 'Enter second whole number.
+ Console.Write("Second number: ") 'Enter second floating-point number.
Dim b As Double = Console.ReadLine
Dim c As Double = a + b
Console.WriteLine(c)
@@ -145,15 +145,15 @@ Module Module1
'Copy and paste the above again.
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
- Console.Write("Second number: ") 'Enter second whole number.
- Dim b As Integer = Console.ReadLine
- Dim c As Integer = a + b
- Dim d As Integer = a * b
- Dim e As Integer = a - b
- Dim f As Integer = a / b
+ Console.Write("Second number: ") 'Enter second floating-point number.
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Dim d As Double = a * b
+ Dim e As Double = a - b
+ Dim f As Double = a / b
'By adding the below lines we are able to calculate the subtract,
- 'multply as well as divide the a and b values
+ 'multiply as well as divide the a and b values
Console.Write(a.ToString() + " + " + b.ToString())
'We want to pad the answers to the left by 3 spaces.
Console.WriteLine(" = " + c.ToString.PadLeft(3))
@@ -179,11 +179,11 @@ Module Module1
Console.Write("First number: ")
Dim a As Double = Console.ReadLine
Console.Write("Second number: ")
- Dim b As Integer = Console.ReadLine
- Dim c As Integer = a + b
- Dim d As Integer = a * b
- Dim e As Integer = a - b
- Dim f As Integer = a / b
+ Dim b As Double = Console.ReadLine
+ Dim c As Double = a + b
+ Dim d As Double = a * b
+ Dim e As Double = a - b
+ Dim f As Double = a / b
Console.Write(a.ToString() + " + " + b.ToString())
Console.WriteLine(" = " + c.ToString.PadLeft(3))
@@ -196,10 +196,10 @@ Module Module1
Console.ReadLine()
'Ask the question, does the user wish to continue? Unfortunately it
'is case sensitive.
- Console.Write("Would you like to continue? (yes / no)")
+ Console.Write("Would you like to continue? (yes / no) ")
'The program grabs the variable and prints and starts again.
answer = Console.ReadLine
- 'The command for the variable to work would be in this case "yes"
+ 'The command for the variable to work would be in this case "yes"
Loop While answer = "yes"
End Sub
@@ -211,7 +211,7 @@ Module Module1
Console.Title = "Using For Loops | Learn X in Y Minutes"
'Declare Variable and what number it should count down in Step -1,
- 'Step -2, Step -3 ect.
+ 'Step -2, Step -3, etc.
For i As Integer = 10 To 0 Step -1
Console.WriteLine(i.ToString) 'Print the value of the counter
Next i 'Calculate new value
@@ -222,7 +222,7 @@ Module Module1
'Eight
Private Sub ConditionalStatement()
Console.Title = "Conditional Statements | Learn X in Y Minutes"
- Dim userName As String = Console.ReadLine
+ Dim userName As String
Console.WriteLine("Hello, What is your name? ") 'Ask the user their name.
userName = Console.ReadLine() 'Stores the users name.
If userName = "Adam" Then
@@ -238,36 +238,34 @@ Module Module1
'Nine
Private Sub IfElseStatement()
- Console.Title = "If / Else Statement | Learn X in Y Minutes"
+ Console.Title = "If / Else Statement | Learn X in Y Minutes"
'Sometimes it is important to consider more than two alternatives.
'Sometimes there are a good few others.
'When this is the case, more than one if statement would be required.
'An if statement is great for vending machines. Where the user enters a code.
- 'A1, A2, A3, ect to select an item.
- 'All choices can be combined into a single if statement.
+ 'A1, A2, A3, etc to select an item.
+ 'All choices can be combined into a single if block.
- Dim selection As String = Console.ReadLine 'Value for selection
- Console.WriteLine("A1. for 7Up")
- Console.WriteLine("A2. for Fanta")
- Console.WriteLine("A3. for Dr. Pepper")
- Console.WriteLine("A4. for Diet Coke")
- Console.ReadLine()
- If selection = "A1" Then
- Console.WriteLine("7up")
- Console.ReadLine()
- ElseIf selection = "A2" Then
- Console.WriteLine("fanta")
- Console.ReadLine()
- ElseIf selection = "A3" Then
- Console.WriteLine("dr. pepper")
- Console.ReadLine()
- ElseIf selection = "A4" Then
- Console.WriteLine("diet coke")
- Console.ReadLine()
- Else
- Console.WriteLine("Please select a product")
- Console.ReadLine()
- End If
+ Dim selection As String 'Declare a variable for selection
+ Console.WriteLine("Please select a product form our lovely vending machine.")
+ Console.WriteLine("A1. for 7Up")
+ Console.WriteLine("A2. for Fanta")
+ Console.WriteLine("A3. for Dr. Pepper")
+ Console.WriteLine("A4. for Diet Coke")
+
+ selection = Console.ReadLine() 'Store a selection from the user
+ If selection = "A1" Then
+ Console.WriteLine("7up")
+ ElseIf selection = "A2" Then
+ Console.WriteLine("fanta")
+ ElseIf selection = "A3" Then
+ Console.WriteLine("dr. pepper")
+ ElseIf selection = "A4" Then
+ Console.WriteLine("diet coke")
+ Else
+ Console.WriteLine("Sorry, I don't have any " + selection)
+ End If
+ Console.ReadLine()
End Sub
diff --git a/whip.html.markdown b/whip.html.markdown
index 61c301a5..e7e5e427 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -9,7 +9,7 @@ filename: whip.lisp
---
Whip is a LISP-dialect made for scripting and simplified concepts.
-It has also borrowed a lot of functions and syntax from Haskell(a non-related language).
+It has also borrowed a lot of functions and syntax from Haskell (a non-related language).
These docs were written by the creator of the language himself. So is this line.
@@ -172,12 +172,12 @@ undefined ; user to indicate a value that hasn't been set
; Comprehensions
; `range` or `..` generates a list of numbers for
-; each number between it's two args.
+; each number between its two args.
(range 1 5) ; => (1 2 3 4 5)
(.. 0 2) ; => (0 1 2)
-; `map` applies it's first arg(which should be a lambda/function)
-; to each item in the following arg(which should be a list)
+; `map` applies its first arg (which should be a lambda/function)
+; to each item in the following arg (which should be a list)
(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4)
; Reduce
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 6e3e2c94..62f08fb9 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -3,6 +3,7 @@ language: yaml
filename: learnyaml.yaml
contributors:
- ["Adam Brenecki", "https://github.com/adambrenecki"]
+ - ["Suhas SG", "https://github.com/jargnar"]
---
YAML is a data serialisation language designed to be directly writable and
@@ -66,14 +67,19 @@ a_nested_map:
# Maps don't have to have string keys.
0.25: a float key
-# Keys can also be multi-line objects, using ? to indicate the start of a key.
+# Keys can also be complex, like multi-line objects
+# We use ? followed by a space to indicate the start of a complex key.
? |
This is a key
that has multiple lines
: and this is its value
-# YAML also allows collection types in keys, but many programming languages
-# will complain.
+# YAML also allows mapping between sequences with the complex key syntax
+# Some language parsers might complain
+# An example
+? - Manchester United
+ - Real Madrid
+: [ 2001-01-01, 2002-02-02 ]
# Sequences (equivalent to lists or arrays) look like this:
a_sequence:
@@ -101,12 +107,31 @@ json_seq: [3, 2, 1, "takeoff"]
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
+# Anchors can be used to duplicate/inherit properties
+base: &base
+ name: Everyone has same name
+
+foo: &foo
+ <<: *base
+ age: 10
+
+bar: &bar
+ <<: *base
+ age: 20
+
+# foo and bar would also have name: Everyone has same name
+
# YAML also has tags, which you can use to explicitly declare types.
explicit_string: !!str 0.5
# Some parsers implement language specific tags, like this one for Python's
# complex number type.
python_complex_number: !!python/complex 1+2j
+# We can also use yaml complex keys with language specific tags
+? !!python/tuple [5, 7]
+: Fifty Seven
+# Would be {(5, 7): 'Fifty Seven'} in python
+
####################
# EXTRA YAML TYPES #
####################
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 28001e3f..3efe4941 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -5,7 +5,8 @@ contributors:
- ["Grant Timmerman", "http://github.com/grant"]
translators:
- ["Xavier Yao", "http://github.com/xavieryao"]
- - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["CY Lim", "http://github.com/cylim"]
lang: zh-cn
---
@@ -13,13 +14,13 @@ Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于20
Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
-亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) ——一个完整的Swift 教程
+亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程
```swift
// 导入外部模块
import UIKit
-//
+//
// MARK: 基础
//
@@ -28,12 +29,14 @@ import UIKit
// TODO: TODO 标记
// FIXME: FIXME 标记
-println("Hello, world")
+// Swift2.0 println() 及 print() 已经整合成 print()。
+print("Hello, world") // 这是原本的 println(),会自动进入下一行
+print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false
// 变量 (var) 的值设置后可以随意改变
// 常量 (let) 的值设置后不能改变
var myVariable = 42
-let øπΩ = "value" // 可以支持 unicode 变量名
+let øπΩ = "value" // 可以支持 unicode 变量名
let π = 3.1415926
let myConstant = 3.1415926
let explicitDouble: Double = 70 // 明确指定变量类型为 Double ,否则编译器将自动推断变量类型
@@ -46,16 +49,17 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串
// 条件编译
// 使用 -D 定义编译开关
#if false
- println("Not printed")
+ print("Not printed")
let buildValue = 3
#else
let buildValue = 7
#endif
-println("Build value: \(buildValue)") // Build value: 7
+print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None
-
+ Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None 。
+ 可在值名称后加个问号 (?) 来表示这个值是 Optional。
+
Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil
Optional<T> 是个枚举类型
@@ -67,13 +71,17 @@ var someOptionalString2: Optional<String> = "optional"
if someOptionalString != nil {
// 变量不为空
if someOptionalString!.hasPrefix("opt") {
- println("has the prefix")
+ print("has the prefix")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
+/*
+ 使用 (!) 可以解决无法访问optional值的运行错误。若要使用 (!)来强制解析,一定要确保 Optional 里不是 nil参数。
+*/
+
// 显式解包 optional 变量
var unwrappedString: String! = "Value is expected."
// 下面语句和上面完全等价,感叹号 (!) 是个后缀运算符,这也是个语法糖
@@ -94,7 +102,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
这里是注释
-
+
/*
支持嵌套的注释
*/
@@ -116,6 +124,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // 使用 let 定义常量,此时 emptyArray 数组不能添加或删除内容
let emptyArray2 = Array<String>() // 与上一语句等价,上一语句更常用
var emptyMutableArray = [String]() // 使用 var 定义变量,可以向 emptyMutableArray 添加数组元素
+var explicitEmptyMutableStringArray: [String] = [] // 与上一语句等价
// 字典
var occupations = [
@@ -126,6 +135,7 @@ occupations["Jayne"] = "Public Relations" // 修改字典,如果 key 不存
let emptyDictionary = [String: Float]() // 使用 let 定义字典常量,字典常量不能修改里面的值
let emptyDictionary2 = Dictionary<String, Float>() // 与上一语句类型等价,上一语句更常用
var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
+var explicitEmptyMutableDictionary: [String: Float] = [:] // 与上一语句类型等价
//
@@ -136,21 +146,21 @@ var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
if value == 1 {
- println("One!")
+ print("One!")
} else {
- println("Not one!")
+ print("Not one!")
}
}
// 字典的 for 循环
var dict = ["one": 1, "two": 2]
for (key, value) in dict {
- println("\(key): \(value)")
+ print("\(key): \(value)")
}
// 区间的 loop 循环:其中 `...` 表示闭环区间,即[-1, 3];`..<` 表示半开闭区间,即[-1,3)
for i in -1...shoppingList.count {
- println(i)
+ print(i)
}
shoppingList[1...2] = ["steak", "peacons"]
// 可以使用 `..<` 来去掉最后一个元素
@@ -163,7 +173,7 @@ while i < 1000 {
// do-while 循环
do {
- println("hello")
+ print("hello")
} while 1 == 2
// Switch 语句
@@ -177,7 +187,7 @@ case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(localScopeValue)?"
-default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
+default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
let vegetableComment = "Everything tastes good in soup."
}
@@ -219,8 +229,8 @@ let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
// 通过下划线 (_) 来忽略不关心的值
let (_, price1, _) = pricesTuple // price1 == 3.69
-println(price1 == pricesTuple.1) // true
-println("Gas price: \(price)")
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
// 可变参数
func setup(numbers: Int...) {
@@ -248,7 +258,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
var someIntA = 7
var someIntB = 3
swapTwoInts(&someIntA, &someIntB)
-println(someIntB) // 7
+print(someIntB) // 7
//
@@ -256,7 +266,7 @@ println(someIntB) // 7
//
var numbers = [1, 2, 6]
-// 函数是闭包的一个特例
+// 函数是闭包的一个特例 ({})
// 闭包实例
// `->` 分隔了闭包的参数和返回值
@@ -296,7 +306,7 @@ print(numbers) // [3, 6, 18]
struct NamesTable {
let names = [String]()
-
+
// 自定义下标运算符
subscript(index: Int) -> String {
return names[index]
@@ -306,7 +316,7 @@ struct NamesTable {
// 结构体有一个自动生成的隐含的命名构造函数
let namesTable = NamesTable(names: ["Me", "Them"])
let name = namesTable[1]
-println("Name is \(name)") // Name is Them
+print("Name is \(name)") // Name is Them
//
// MARK: 类
@@ -329,7 +339,7 @@ public class Shape {
internal class Rect: Shape {
// 值属性 (Stored properties)
var sideLength: Int = 1
-
+
// 计算属性 (Computed properties)
private var perimeter: Int {
get {
@@ -340,11 +350,11 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
// 延时加载的属性,只有这个属性第一次被引用时才进行初始化,而不是定义时就初始化
// subShape 值为 nil ,直到 subShape 第一次被引用时才初始化为一个 Rect 实例
lazy var subShape = Rect(sideLength: 4)
-
+
// 监控属性值的变化。
// 当我们需要在属性值改变时做一些事情,可以使用 `willSet` 和 `didSet` 来设置监控函数
// `willSet`: 值改变之前被调用
@@ -352,14 +362,14 @@ internal class Rect: Shape {
var identifier: String = "defaultID" {
// `willSet` 的参数是即将设置的新值,参数名可以指定,如果没有指定,就是 `newValue`
willSet(someIdentifier) {
- println(someIdentifier)
+ print(someIdentifier)
}
// `didSet` 的参数是已经被覆盖掉的旧的值,参数名也可以指定,如果没有指定,就是 `oldValue`
didSet {
- println(oldValue)
+ print(oldValue)
}
}
-
+
// 命名构造函数 (designated inits),它必须初始化所有的成员变量,
// 然后调用父类的命名构造函数继续初始化父类的所有变量。
init(sideLength: Int) {
@@ -367,13 +377,13 @@ internal class Rect: Shape {
// 必须显式地在构造函数最后调用父类的构造函数 super.init
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
--sideLength
}
}
-
+
// 函数重载使用 override 关键字
override func getArea() -> Int {
return sideLength * sideLength
@@ -394,16 +404,16 @@ class Square: Rect {
}
var mySquare = Square()
-println(mySquare.getArea()) // 25
+print(mySquare.getArea()) // 25
mySquare.shrink()
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 类型转换
let aShape = mySquare as Shape
// 使用三个等号来比较是不是同一个实例
if mySquare === aShape {
- println("Yep, it's mySquare")
+ print("Yep, it's mySquare")
}
class Circle: Shape {
@@ -411,12 +421,12 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// optional 构造函数,可能会返回 nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -425,13 +435,13 @@ class Circle: Shape {
// 根据 Swift 类型推断,myCircle 是 Optional<Circle> 类型的变量
var myCircle = Circle(radius: 1)
-println(myCircle?.getArea()) // Optional(3)
-println(myCircle!.getArea()) // 3
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
var myEmptyCircle = Circle(radius: -1)
-println(myEmptyCircle?.getArea()) // "nil"
+print(myEmptyCircle?.getArea()) // "nil"
if let circle = myEmptyCircle {
// 此语句不会输出,因为 myEmptyCircle 变量值为 nil
- println("circle is not nil")
+ print("circle is not nil")
}
@@ -461,7 +471,7 @@ enum BookName: String {
case John = "John"
case Luke = "Luke"
}
-println("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.John.rawValue)")
// 与特定数据类型关联的枚举
enum Furniture {
@@ -469,7 +479,7 @@ enum Furniture {
case Desk(height: Int)
// 和 String, Int 关联的枚举记录
case Chair(brand: String, height: Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -481,9 +491,9 @@ enum Furniture {
}
var desk: Furniture = .Desk(height: 80)
-println(desk.description()) // "Desk with 80 cm"
+print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair(brand: "Foo", height: 40)
-println(chair.description()) // "Chair of Foo with 40 cm"
+print(chair.description()) // "Chair of Foo with 40 cm"
//
@@ -512,7 +522,7 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
@@ -539,21 +549,21 @@ extension Square: Printable {
}
}
-println("Square: \(mySquare)") // Area: 16 - ID: defaultID
+print("Square: \(mySquare)") // Area: 16 - ID: defaultID
// 也可以给系统内置类型添加功能支持
extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
}
-println(7.customProperty) // "This is 7"
-println(14.multiplyBy(3)) // 42
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。
// 如果只有一个类型限制,可以省略 `where` 关键字
@@ -566,7 +576,7 @@ func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
return nil
}
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
-println(foundAtIndex == 2) // true
+print(foundAtIndex == 2) // true
// 自定义运算符:
// 自定义运算符可以以下面的字符打头:
@@ -581,11 +591,24 @@ prefix func !!! (inout shape: Square) -> Square {
}
// 当前值
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 使用自定义的 !!! 运算符来把矩形边长放大三倍
!!!mySquare
-println(mySquare.sideLength) // 12
+print(mySquare.sideLength) // 12
-```
+// 运算符也可以是泛型
+infix operator <-> {}
+func <-><T: Equatable> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
+
+```