mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-01-17 21:49:22 +01:00
Merge remote-tracking branch 'adambard/master'
Conflicts: java.html.markdown
This commit is contained in:
commit
fc3c56ee93
@ -633,7 +633,7 @@ writeln( toThisArray );
|
|||||||
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
|
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
|
||||||
// exhibits a runtime error.
|
// exhibits a runtime error.
|
||||||
// Even though the domain of the array and the loop-expression are
|
// Even though the domain of the array and the loop-expression are
|
||||||
// the same size, the body of the expression can be though of as an iterator.
|
// the same size, the body of the expression can be thought of as an iterator.
|
||||||
// Because iterators can yield nothing, that iterator yields a different number
|
// Because iterators can yield nothing, that iterator yields a different number
|
||||||
// of things than the domain of the array or loop, which is not allowed.
|
// of things than the domain of the array or loop, which is not allowed.
|
||||||
|
|
||||||
|
@ -57,7 +57,7 @@ math =
|
|||||||
# "root": Math.sqrt,
|
# "root": Math.sqrt,
|
||||||
# "square": square,
|
# "square": square,
|
||||||
# "cube": function(x) { return x * square(x); }
|
# "cube": function(x) { return x * square(x); }
|
||||||
#}
|
# };
|
||||||
|
|
||||||
# Splats:
|
# Splats:
|
||||||
race = (winner, runners...) ->
|
race = (winner, runners...) ->
|
||||||
|
@ -8,13 +8,17 @@ lang: fr-fr
|
|||||||
|
|
||||||
Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de
|
Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de
|
||||||
représentation de données par sérialisation, conçu pour être aisément
|
représentation de données par sérialisation, conçu pour être aisément
|
||||||
éditable et lisible par nous même, les humains.
|
modifiable et lisible par nous-mêmes, les humains.
|
||||||
|
|
||||||
YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages.
|
YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le
|
||||||
|
découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont
|
||||||
|
il est un parent naturel. Toutefois, YAML emprunte également des idées et
|
||||||
|
concepts de Python, et s'intègre bien avec bon nombre de langages.
|
||||||
|
Contrairement à ce dernier, YAML interdit l'utilisation des tabulations.
|
||||||
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# les Commentaires sont précédés d'un signe "#", comme cette ligne.
|
# Les commentaires sont précédés d'un signe "#", comme cette ligne.
|
||||||
|
|
||||||
#############
|
#############
|
||||||
# SCALAIRES #
|
# SCALAIRES #
|
||||||
@ -27,67 +31,67 @@ YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le d
|
|||||||
# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
|
# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
|
||||||
# hash ou objet dans d'autres langages.
|
# hash ou objet dans d'autres langages.
|
||||||
clé: valeur
|
clé: valeur
|
||||||
aurtre_clé: une autre valeur
|
autre_clé: une autre valeur
|
||||||
valeur_numérique: 100
|
valeur_numérique: 100
|
||||||
notation_scientifique: 1e+12
|
notation_scientifique: 1e+12
|
||||||
boolean: true
|
booléen: true
|
||||||
valeur_null: null
|
valeur_null: null
|
||||||
clé avec espaces: valeur
|
clé avec espaces: valeur
|
||||||
# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères
|
# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères
|
||||||
# entre guillemets, cela reste possible, et parfois utile.
|
# entre guillemets, cela reste possible, et parfois utile.
|
||||||
toutefois: "Une chaîne, peut être contenue entre guillemets."
|
toutefois: "Une chaîne, peut être contenue entre guillemets."
|
||||||
"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé."
|
"Une clé entre guillemets.": "Utile si l'on veut utiliser ':' dans la clé."
|
||||||
|
|
||||||
# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
|
# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
|
||||||
# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ).
|
# comme un "bloc littéral" (avec '|') ou bien un "bloc replié" (avec '>').
|
||||||
bloc_littéral: |
|
bloc_littéral: |
|
||||||
Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral',
|
Tout ce bloc de texte sera la valeur de la clé "bloc_littéral",
|
||||||
avec préservation des retours à la ligne. ( chaque ligne vide à
|
avec préservation des retours à la ligne.
|
||||||
l'intérieur du même bloc, sera remplacée par "\n\n" )
|
|
||||||
|
|
||||||
Le littéral continue jusqu'à ce que l'indentation soit annulée.
|
Le littéral continue jusqu'à ce que l'indentation soit annulée.
|
||||||
|
|
||||||
Toutes lignes qui serait "d'avantage indentées" conservent leur
|
Toutes lignes qui seraient "davantage indentées" conservent leur
|
||||||
indentation, constituée de 4 espaces.
|
indentation, constituée de 4 espaces.
|
||||||
bloc_replié: >
|
bloc_replié: >
|
||||||
Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais
|
Tout ce bloc de texte sera la valeur de la clé "bloc_replié", mais
|
||||||
cette fois ci, toutes les nouvelles lignes deviendront un simple espace.
|
cette fois-ci, toutes les nouvelles lignes deviendront un simple espace.
|
||||||
|
|
||||||
Les lignes vides, comme ci-dessus, seront converties en caractère "\n".
|
Les lignes vides, comme ci-dessus, seront converties en caractère de
|
||||||
|
nouvelle ligne.
|
||||||
|
|
||||||
Les lignes 'plus-indentées' gardent leurs retours à la ligne -
|
Les lignes "plus-indentées" gardent leurs retours à la ligne -
|
||||||
ce texte apparaîtra sur deux lignes.
|
ce texte apparaîtra sur deux lignes.
|
||||||
|
|
||||||
###############
|
###############
|
||||||
# COLLECTIONS #
|
# COLLECTIONS #
|
||||||
###############
|
###############
|
||||||
|
|
||||||
# l'Imbrication est créée par indentation.
|
# L'imbrication est créée par indentation.
|
||||||
une_map_imbriquée:
|
une_map_imbriquée:
|
||||||
clé: valeur
|
clé: valeur
|
||||||
autre_clé: autre valeur
|
autre_clé: autre valeur
|
||||||
autre_map_imbriquée:
|
autre_map_imbriquée:
|
||||||
bonjour: bonjour
|
bonjour: bonjour
|
||||||
|
|
||||||
# les Clés des Maps ne sont pas nécessairement des chaînes de caractères.
|
# Les clés des maps ne sont pas nécessairement des chaînes de caractères.
|
||||||
0.25: une clé de type float
|
0.25: une clé de type flottant
|
||||||
|
|
||||||
# les Clés peuvent également être des objets s'étendant sur plusieurs lignes,
|
# Les clés peuvent également être des objets s'étendant sur plusieurs lignes,
|
||||||
# en utilisant le signe "?" pour indiquer le début de la clé.
|
# en utilisant le signe "?" pour indiquer le début de la clé.
|
||||||
? |
|
? |
|
||||||
ceci est une Clé
|
ceci est une clé
|
||||||
sur de multiples lignes
|
sur de multiples lignes
|
||||||
: et ceci est sa Valeur
|
: et ceci est sa valeur
|
||||||
|
|
||||||
# YAML autorise aussi l'usage des collections à l'intérieur des clés,
|
# YAML autorise aussi l'usage des collections à l'intérieur des clés,
|
||||||
# mais certains langages de programmation ne le tolère pas si bien.
|
# mais certains langages de programmation ne le tolère pas si bien.
|
||||||
|
|
||||||
# les Séquences (équivalent des listes ou tableaux) ressemblent à cela:
|
# Les séquences (équivalent des listes ou tableaux) ressemblent à cela :
|
||||||
une_séquence:
|
une_séquence:
|
||||||
- Item 1
|
- Objet 1
|
||||||
- Item 2
|
- Objet 2
|
||||||
- 0.5 # les séquences peuvent contenir des types variés.
|
- 0.5 # les séquences peuvent contenir des types variés.
|
||||||
- Item 4
|
- Objet 4
|
||||||
- clé: valeur
|
- clé: valeur
|
||||||
autre_clé: autre_valeur
|
autre_clé: autre_valeur
|
||||||
-
|
-
|
||||||
@ -99,22 +103,22 @@ une_séquence:
|
|||||||
json_map: {"clé": "valeur"}
|
json_map: {"clé": "valeur"}
|
||||||
json_seq: [1, 2, 3, "soleil"]
|
json_seq: [1, 2, 3, "soleil"]
|
||||||
|
|
||||||
#################################
|
################################
|
||||||
# AUTRES FONCTIONNALITÉES YAML #
|
# AUTRES FONCTIONNALITÉES YAML #
|
||||||
#################################
|
################################
|
||||||
|
|
||||||
# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci
|
# YAML possède une fonctionnalité fort utile nommée "ancres". Celle-ci
|
||||||
# vous permet de dupliquer aisément du contenu au sein de votre document.
|
# vous permet de dupliquer aisément du contenu au sein de votre document.
|
||||||
|
|
||||||
# Les deux clés suivantes auront la même valeur :
|
# Les deux clés suivantes auront la même valeur :
|
||||||
contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés.
|
contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés.
|
||||||
autre_ancre: *nom_ancre
|
autre_ancre: *nom_ancre
|
||||||
|
|
||||||
# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données.
|
# Avec les tags YAML, vous pouvez explicitement déclarer des types de données.
|
||||||
chaine_explicite: !!str 0.5
|
chaine_explicite: !!str 0.5
|
||||||
|
|
||||||
# Certains parsers implémentent des tags spécifiques à d'autres langages,
|
# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à
|
||||||
# comme par exemple le "complex number" de Python.
|
# d'autres langages, comme par exemple celui des nombres complexes de Python.
|
||||||
python_complex_number: !!python/complex 1+2j
|
python_complex_number: !!python/complex 1+2j
|
||||||
|
|
||||||
#####################
|
#####################
|
||||||
@ -135,7 +139,7 @@ fichier_gif: !!binary |
|
|||||||
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
|
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
|
||||||
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
|
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
|
||||||
|
|
||||||
# YAML a de même un type "set", qui ressemble à cela:
|
# YAML a de même un type "set", semblable à ceci :
|
||||||
set:
|
set:
|
||||||
? item1
|
? item1
|
||||||
? item2
|
? item2
|
||||||
@ -152,6 +156,6 @@ set2:
|
|||||||
|
|
||||||
Quelques références et outils :
|
Quelques références et outils :
|
||||||
|
|
||||||
- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
|
- Documentation officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
|
||||||
- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire,
|
- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire,
|
||||||
- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
|
- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
|
||||||
|
@ -119,7 +119,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
|
|||||||
// ================================================
|
// ================================================
|
||||||
|
|
||||||
// F# is a true functional language -- functions are first
|
// F# is a true functional language -- functions are first
|
||||||
// class entities and can be combined easy to make powerful
|
// class entities and can be combined easily to make powerful
|
||||||
// constructs
|
// constructs
|
||||||
|
|
||||||
// Modules are used to group functions together
|
// Modules are used to group functions together
|
||||||
|
@ -10,6 +10,7 @@ contributors:
|
|||||||
- ["Quint Guvernator", "https://github.com/qguv"]
|
- ["Quint Guvernator", "https://github.com/qguv"]
|
||||||
- ["Jose Donizetti", "https://github.com/josedonizetti"]
|
- ["Jose Donizetti", "https://github.com/josedonizetti"]
|
||||||
- ["Alexej Friesen", "https://github.com/heyalexej"]
|
- ["Alexej Friesen", "https://github.com/heyalexej"]
|
||||||
|
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||||
---
|
---
|
||||||
|
|
||||||
Go was created out of the need to get work done. It's not the latest trend
|
Go was created out of the need to get work done. It's not the latest trend
|
||||||
@ -115,7 +116,7 @@ can include line breaks.` // Same string type.
|
|||||||
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
|
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
|
||||||
// To append another slice, instead of list of atomic elements we can
|
// To append another slice, instead of list of atomic elements we can
|
||||||
// pass a reference to a slice or a slice literal like this, with a
|
// pass a reference to a slice or a slice literal like this, with a
|
||||||
// trailing elipsis, meaning take a slice and unpack its elements,
|
// trailing ellipsis, meaning take a slice and unpack its elements,
|
||||||
// appending them to slice s.
|
// appending them to slice s.
|
||||||
s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
|
s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
|
||||||
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
|
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
|
||||||
@ -129,7 +130,7 @@ can include line breaks.` // Same string type.
|
|||||||
m["one"] = 1
|
m["one"] = 1
|
||||||
|
|
||||||
// Unused variables are an error in Go.
|
// Unused variables are an error in Go.
|
||||||
// The underbar lets you "use" a variable but discard its value.
|
// The underscore lets you "use" a variable but discard its value.
|
||||||
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
|
_, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
|
||||||
// Output of course counts as using a variable.
|
// Output of course counts as using a variable.
|
||||||
fmt.Println(s, c, a4, s3, d2, m)
|
fmt.Println(s, c, a4, s3, d2, m)
|
||||||
@ -164,7 +165,7 @@ func expensiveComputation() float64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func learnFlowControl() {
|
func learnFlowControl() {
|
||||||
// If statements require brace brackets, and do not require parens.
|
// If statements require brace brackets, and do not require parentheses.
|
||||||
if true {
|
if true {
|
||||||
fmt.Println("told ya")
|
fmt.Println("told ya")
|
||||||
}
|
}
|
||||||
@ -407,6 +408,8 @@ func requestServer() {
|
|||||||
|
|
||||||
The root of all things Go is the [official Go web site](http://golang.org/).
|
The root of all things Go is the [official Go web site](http://golang.org/).
|
||||||
There you can follow the tutorial, play interactively, and read lots.
|
There you can follow the tutorial, play interactively, and read lots.
|
||||||
|
Aside from a tour, [the docs](https://golang.org/doc/) contain information on
|
||||||
|
how to write clean and effective Go code, package and command docs, and release history.
|
||||||
|
|
||||||
The language definition itself is highly recommended. It's easy to read
|
The language definition itself is highly recommended. It's easy to read
|
||||||
and amazingly short (as language definitions go these days.)
|
and amazingly short (as language definitions go these days.)
|
||||||
|
@ -5,6 +5,7 @@ contributors:
|
|||||||
- ["Jakukyo Friel", "http://weakish.github.io"]
|
- ["Jakukyo Friel", "http://weakish.github.io"]
|
||||||
- ["Madison Dickson", "http://github.com/mix3d"]
|
- ["Madison Dickson", "http://github.com/mix3d"]
|
||||||
- ["Simon Morgan", "http://sjm.io/"]
|
- ["Simon Morgan", "http://sjm.io/"]
|
||||||
|
- ["Zachary Ferguson", "http://github.com/zfergus2"]
|
||||||
filename: LearnJava.java
|
filename: LearnJava.java
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -31,7 +32,7 @@ import java.security.*;
|
|||||||
// the file.
|
// the file.
|
||||||
public class LearnJava {
|
public class LearnJava {
|
||||||
|
|
||||||
// A program must have a main method as an entry point.
|
// In order to run a java program, it must have a main method as an entry point.
|
||||||
public static void main (String[] args) {
|
public static void main (String[] args) {
|
||||||
|
|
||||||
// Use System.out.println() to print lines.
|
// Use System.out.println() to print lines.
|
||||||
@ -45,6 +46,8 @@ public class LearnJava {
|
|||||||
System.out.print("Hello ");
|
System.out.print("Hello ");
|
||||||
System.out.print("World");
|
System.out.print("World");
|
||||||
|
|
||||||
|
// Use System.out.printf() for easy formatted printing.
|
||||||
|
System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
|
||||||
|
|
||||||
///////////////////////////////////////
|
///////////////////////////////////////
|
||||||
// Variables
|
// Variables
|
||||||
@ -93,7 +96,7 @@ public class LearnJava {
|
|||||||
|
|
||||||
// Float - Single-precision 32-bit IEEE 754 Floating Point
|
// Float - Single-precision 32-bit IEEE 754 Floating Point
|
||||||
float fooFloat = 234.5f;
|
float fooFloat = 234.5f;
|
||||||
// f is used to denote that this variable value is of type float;
|
// f or F is used to denote that this variable value is of type float;
|
||||||
// otherwise it is treated as double.
|
// otherwise it is treated as double.
|
||||||
|
|
||||||
// Double - Double-precision 64-bit IEEE 754 Floating Point
|
// Double - Double-precision 64-bit IEEE 754 Floating Point
|
||||||
@ -106,8 +109,11 @@ public class LearnJava {
|
|||||||
// Char - A single 16-bit Unicode character
|
// Char - A single 16-bit Unicode character
|
||||||
char fooChar = 'A';
|
char fooChar = 'A';
|
||||||
|
|
||||||
// final variables can't be reassigned to another object.
|
// final variables can't be reassigned to another object,
|
||||||
final int HOURS_I_WORK_PER_WEEK = 9001;
|
final int HOURS_I_WORK_PER_WEEK = 9001;
|
||||||
|
// but they can be initialized later.
|
||||||
|
final double E;
|
||||||
|
E = 2.71828;
|
||||||
|
|
||||||
// Strings
|
// Strings
|
||||||
String fooString = "My String Is Here!";
|
String fooString = "My String Is Here!";
|
||||||
@ -166,6 +172,7 @@ public class LearnJava {
|
|||||||
System.out.println("2-1 = " + (i2 - i1)); // => 1
|
System.out.println("2-1 = " + (i2 - i1)); // => 1
|
||||||
System.out.println("2*1 = " + (i2 * i1)); // => 2
|
System.out.println("2*1 = " + (i2 * i1)); // => 2
|
||||||
System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
|
System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down)
|
||||||
|
System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5
|
||||||
|
|
||||||
// Modulo
|
// Modulo
|
||||||
System.out.println("11%3 = "+(11 % 3)); // => 2
|
System.out.println("11%3 = "+(11 % 3)); // => 2
|
||||||
@ -178,12 +185,17 @@ public class LearnJava {
|
|||||||
System.out.println("2 <= 2? " + (2 <= 2)); // => true
|
System.out.println("2 <= 2? " + (2 <= 2)); // => true
|
||||||
System.out.println("2 >= 2? " + (2 >= 2)); // => true
|
System.out.println("2 >= 2? " + (2 >= 2)); // => true
|
||||||
|
|
||||||
|
// Boolean operators
|
||||||
|
System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
|
||||||
|
System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
|
||||||
|
System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
|
||||||
|
|
||||||
// Bitwise operators!
|
// Bitwise operators!
|
||||||
/*
|
/*
|
||||||
~ Unary bitwise complement
|
~ Unary bitwise complement
|
||||||
<< Signed left shift
|
<< Signed left shift
|
||||||
>> Signed right shift
|
>> Signed/Arithmetic right shift
|
||||||
>>> Unsigned right shift
|
>>> Unsigned/Logical right shift
|
||||||
& Bitwise AND
|
& Bitwise AND
|
||||||
^ Bitwise exclusive OR
|
^ Bitwise exclusive OR
|
||||||
| Bitwise inclusive OR
|
| Bitwise inclusive OR
|
||||||
@ -236,9 +248,8 @@ public class LearnJava {
|
|||||||
System.out.println("fooDoWhile Value: " + fooDoWhile);
|
System.out.println("fooDoWhile Value: " + fooDoWhile);
|
||||||
|
|
||||||
// For Loop
|
// For Loop
|
||||||
int fooFor;
|
|
||||||
// for loop structure => for(<start_statement>; <conditional>; <step>)
|
// for loop structure => for(<start_statement>; <conditional>; <step>)
|
||||||
for (fooFor = 0; fooFor < 10; fooFor++) {
|
for (int fooFor = 0; fooFor < 10; fooFor++) {
|
||||||
System.out.println(fooFor);
|
System.out.println(fooFor);
|
||||||
// Iterated 10 times, fooFor 0->9
|
// Iterated 10 times, fooFor 0->9
|
||||||
}
|
}
|
||||||
@ -357,7 +368,8 @@ public class LearnJava {
|
|||||||
} // End LearnJava class
|
} // End LearnJava class
|
||||||
|
|
||||||
|
|
||||||
// You can include other, non-public outer-level classes in a .java file
|
// You can include other, non-public outer-level classes in a .java file,
|
||||||
|
// but it is good practice. Instead split classes into separate files.
|
||||||
|
|
||||||
|
|
||||||
// Class Declaration Syntax:
|
// Class Declaration Syntax:
|
||||||
@ -377,6 +389,8 @@ class Bicycle {
|
|||||||
// Constructors are a way of creating classes
|
// Constructors are a way of creating classes
|
||||||
// This is a constructor
|
// This is a constructor
|
||||||
public Bicycle() {
|
public Bicycle() {
|
||||||
|
// You can also call another constructor:
|
||||||
|
// this(1, 50, 5, "Bontrager");
|
||||||
gear = 1;
|
gear = 1;
|
||||||
cadence = 50;
|
cadence = 50;
|
||||||
speed = 5;
|
speed = 5;
|
||||||
@ -392,13 +406,13 @@ class Bicycle {
|
|||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function Syntax:
|
// Method Syntax:
|
||||||
// <public/private/protected> <return type> <function name>(<args>)
|
// <public/private/protected> <return type> <function name>(<args>)
|
||||||
|
|
||||||
// Java classes often implement getters and setters for their fields
|
// Java classes often implement getters and setters for their fields
|
||||||
|
|
||||||
// Method declaration syntax:
|
// Method declaration syntax:
|
||||||
// <scope> <return type> <method name>(<args>)
|
// <access modifier> <return type> <method name>(<args>)
|
||||||
public int getCadence() {
|
public int getCadence() {
|
||||||
return cadence;
|
return cadence;
|
||||||
}
|
}
|
||||||
@ -429,7 +443,7 @@ class Bicycle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Method to display the attribute values of this Object.
|
//Method to display the attribute values of this Object.
|
||||||
@Override
|
@Override // Inherited from the Object class.
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
|
return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
|
||||||
" name: " + name;
|
" name: " + name;
|
||||||
@ -476,6 +490,7 @@ public interface Digestible {
|
|||||||
// We can now create a class that implements both of these interfaces.
|
// We can now create a class that implements both of these interfaces.
|
||||||
public class Fruit implements Edible, Digestible {
|
public class Fruit implements Edible, Digestible {
|
||||||
@Override
|
@Override
|
||||||
|
<<<<<<< HEAD
|
||||||
public void eat() {
|
public void eat() {
|
||||||
// awesome code goes here
|
// awesome code goes here
|
||||||
}
|
}
|
||||||
@ -484,6 +499,16 @@ public class Fruit implements Edible, Digestible {
|
|||||||
public void digest() {
|
public void digest() {
|
||||||
// awesome code goes here
|
// awesome code goes here
|
||||||
}
|
}
|
||||||
|
=======
|
||||||
|
public void eat() {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void digest() {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
>>>>>>> adambard/master
|
||||||
}
|
}
|
||||||
|
|
||||||
// In Java, you can extend only one class, but you can implement many
|
// In Java, you can extend only one class, but you can implement many
|
||||||
@ -491,6 +516,7 @@ public class Fruit implements Edible, Digestible {
|
|||||||
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||||
InterfaceTwo {
|
InterfaceTwo {
|
||||||
@Override
|
@Override
|
||||||
|
<<<<<<< HEAD
|
||||||
public void InterfaceOneMethod() {
|
public void InterfaceOneMethod() {
|
||||||
// awesome code goes here
|
// awesome code goes here
|
||||||
}
|
}
|
||||||
@ -499,20 +525,31 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
|||||||
public void InterfaceTwoMethod() {
|
public void InterfaceTwoMethod() {
|
||||||
// awesome code goes here
|
// awesome code goes here
|
||||||
}
|
}
|
||||||
|
=======
|
||||||
|
public void InterfaceOneMethod() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void InterfaceTwoMethod() {
|
||||||
|
}
|
||||||
|
>>>>>>> adambard/master
|
||||||
|
}
|
||||||
|
|
||||||
// Abstract Classes
|
// Abstract Classes
|
||||||
|
|
||||||
// Abstract Class declaration syntax
|
// Abstract Class declaration syntax
|
||||||
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
|
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
|
||||||
// // Constants and variables
|
// // Constants and variables
|
||||||
// // Method declarations
|
// // Method declarations
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// Methods can't have bodies in an interface, unless the method is
|
// Marking a class as abstract means that it contains abstract methods that must
|
||||||
// static. Also variables are NOT final by default, unlike an interface.
|
// be defined in a child class. Similar to interfaces, abstract classes cannot
|
||||||
// Also abstract classes CAN have the "main" method.
|
// be instantiated, but instead must be extended and the abstract methods
|
||||||
// Abstract classes solve these problems.
|
// defined. Different from interfaces, abstract classes can contain a mixture of
|
||||||
|
// concrete and abstract methods. Methods in an interface cannot have a body,
|
||||||
|
// unless the method is static, and variables are final by default, unlike an
|
||||||
|
// abstract class. Also abstract classes CAN have the "main" method.
|
||||||
|
|
||||||
public abstract class Animal
|
public abstract class Animal
|
||||||
{
|
{
|
||||||
@ -529,7 +566,7 @@ public abstract class Animal
|
|||||||
// No need to initialize, however in an interface
|
// No need to initialize, however in an interface
|
||||||
// a variable is implicitly final and hence has
|
// a variable is implicitly final and hence has
|
||||||
// to be initialized.
|
// to be initialized.
|
||||||
private int age;
|
protected int age;
|
||||||
|
|
||||||
public void printAge()
|
public void printAge()
|
||||||
{
|
{
|
||||||
@ -568,6 +605,42 @@ class Dog extends Animal
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Final Classes
|
||||||
|
|
||||||
|
// Final Class declaration syntax
|
||||||
|
// <access-level> final <final-class-name> {
|
||||||
|
// // Constants and variables
|
||||||
|
// // Method declarations
|
||||||
|
// }
|
||||||
|
|
||||||
|
// Final classes are classes that cannot be inherited from and are therefore a
|
||||||
|
// final child. In a way, final classes are the opposite of abstract classes
|
||||||
|
// because abstract classes must be extended, but final classes cannot be
|
||||||
|
// extended.
|
||||||
|
public final class SaberToothedCat extends Animal
|
||||||
|
{
|
||||||
|
// Note still have to override the abstract methods in the
|
||||||
|
// abstract class.
|
||||||
|
@Override
|
||||||
|
public void makeSound()
|
||||||
|
{
|
||||||
|
System.out.println("Roar");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Final Methods
|
||||||
|
public abstract class Mammal()
|
||||||
|
{
|
||||||
|
// Final Method Syntax:
|
||||||
|
// <access modifier> final <return type> <function name>(<args>)
|
||||||
|
|
||||||
|
// Final methods, like, final classes cannot be overridden by a child class,
|
||||||
|
// and are therefore the final implementation of the method.
|
||||||
|
public final boolean isWarmBlooded()
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Further Reading
|
## Further Reading
|
||||||
|
@ -218,6 +218,26 @@ for (var i = 0; i < 5; i++){
|
|||||||
// will run 5 times
|
// will run 5 times
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//The For/In statement loops iterates over every property across the entire prototype chain
|
||||||
|
var description = "";
|
||||||
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
|
for (var x in person){
|
||||||
|
description += person[x] + " ";
|
||||||
|
}
|
||||||
|
|
||||||
|
//If only want to consider properties attached to the object itself,
|
||||||
|
//and not its prototypes use hasOwnProperty() check
|
||||||
|
var description = "";
|
||||||
|
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||||
|
for (var x in person){
|
||||||
|
if (person.hasOwnProperty(x)){
|
||||||
|
description += person[x] + " ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//for/in should not be used to iterate over an Array where the index order is important.
|
||||||
|
//There is no guarantee that for/in will return the indexes in any particular order
|
||||||
|
|
||||||
// && is logical and, || is logical or
|
// && is logical and, || is logical or
|
||||||
if (house.size == "big" && house.colour == "blue"){
|
if (house.size == "big" && house.colour == "blue"){
|
||||||
house.contains = "bear";
|
house.contains = "bear";
|
||||||
|
@ -10,8 +10,11 @@ As JSON is an extremely simple data-interchange format, this is most likely goin
|
|||||||
to be the simplest Learn X in Y Minutes ever.
|
to be the simplest Learn X in Y Minutes ever.
|
||||||
|
|
||||||
JSON in its purest form has no actual comments, but most parsers will accept
|
JSON in its purest form has no actual comments, but most parsers will accept
|
||||||
C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is
|
C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma
|
||||||
going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
(i.e. a comma after the last element of an array or the after the last property of an object),
|
||||||
|
but they should be avoided for better compatibility.
|
||||||
|
|
||||||
|
For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
|
@ -235,7 +235,7 @@ proc ask(question: string): Answer =
|
|||||||
else: echo("Please be clear: yes or no")
|
else: echo("Please be clear: yes or no")
|
||||||
|
|
||||||
proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing
|
proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing
|
||||||
assert(amount > 0 or amount < 9000, "Crazy Sugar")
|
assert(amount > 0 and amount < 9000, "Crazy Sugar")
|
||||||
for a in 1..amount:
|
for a in 1..amount:
|
||||||
echo(a, " sugar...")
|
echo(a, " sugar...")
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ minimalistische Turing-complete programmeertaal met maar acht commando's.
|
|||||||
```
|
```
|
||||||
Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd.
|
Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd.
|
||||||
|
|
||||||
Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel
|
Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel
|
||||||
gevuld is met nullen en een pointer die wijst naar de huidige cel.
|
gevuld is met nullen en een pointer die wijst naar de huidige cel.
|
||||||
|
|
||||||
Dit zijn de acht commando's:
|
Dit zijn de acht commando's:
|
||||||
|
@ -132,7 +132,7 @@ sub with-named($normal-arg, :$named) {
|
|||||||
with-named(1, named => 6); #=> 7
|
with-named(1, named => 6); #=> 7
|
||||||
# There's one gotcha to be aware of, here:
|
# There's one gotcha to be aware of, here:
|
||||||
# If you quote your key, Perl 6 won't be able to see it at compile time,
|
# If you quote your key, Perl 6 won't be able to see it at compile time,
|
||||||
# and you'll have a single Pair object as a positional paramater,
|
# and you'll have a single Pair object as a positional parameter,
|
||||||
# which means this fails:
|
# which means this fails:
|
||||||
with-named(1, 'named' => 6);
|
with-named(1, 'named' => 6);
|
||||||
|
|
||||||
@ -197,7 +197,7 @@ sub mutate($n is rw) {
|
|||||||
say "\$n is now $n !";
|
say "\$n is now $n !";
|
||||||
}
|
}
|
||||||
|
|
||||||
# If what you want is a copy instead, use `is copy`.
|
# If what you want a copy instead, use `is copy`.
|
||||||
|
|
||||||
# A sub itself returns a container, which means it can be marked as rw:
|
# A sub itself returns a container, which means it can be marked as rw:
|
||||||
my $x = 42;
|
my $x = 42;
|
||||||
@ -234,7 +234,7 @@ say "Quite truthy" if True;
|
|||||||
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
|
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
|
||||||
my $a = $condition ?? $value-if-true !! $value-if-false;
|
my $a = $condition ?? $value-if-true !! $value-if-false;
|
||||||
|
|
||||||
# - `given`-`when` looks like other languages `switch`, but much more
|
# - `given`-`when` looks like other languages' `switch`, but much more
|
||||||
# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
|
# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
|
||||||
#
|
#
|
||||||
# This variable contains the default argument of a block,
|
# This variable contains the default argument of a block,
|
||||||
@ -1429,7 +1429,7 @@ for <well met young hero we shall meet later> {
|
|||||||
# A flip-flop can change state as many times as needed:
|
# A flip-flop can change state as many times as needed:
|
||||||
for <test start print it stop not printing start print again stop not anymore> {
|
for <test start print it stop not printing start print again stop not anymore> {
|
||||||
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
|
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
|
||||||
#=> "print this printing again"
|
#=> "print it print again"
|
||||||
}
|
}
|
||||||
|
|
||||||
# you might also use a Whatever Star,
|
# you might also use a Whatever Star,
|
||||||
@ -1461,4 +1461,3 @@ If you want to go further, you can:
|
|||||||
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
|
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
|
||||||
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
|
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
|
||||||
- Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
|
- Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
|
||||||
|
|
||||||
|
@ -693,8 +693,43 @@ use My\Namespace as SomeOtherNamespace;
|
|||||||
|
|
||||||
$cls = new SomeOtherNamespace\MyClass();
|
$cls = new SomeOtherNamespace\MyClass();
|
||||||
|
|
||||||
|
/**********************
|
||||||
|
* Error Handling
|
||||||
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// Simple error handling can be done with try catch block
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Do something
|
||||||
|
} catch ( Exception $e) {
|
||||||
|
// Handle exception
|
||||||
|
}
|
||||||
|
|
||||||
|
// When using try catch blocks in a namespaced enviroment use the following
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Do something
|
||||||
|
} catch (\Exception $e) {
|
||||||
|
// Handle exception
|
||||||
|
}
|
||||||
|
|
||||||
|
// Custom exceptions
|
||||||
|
|
||||||
|
class MyException extends Exception {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
$condition = true;
|
||||||
|
|
||||||
|
if ($condition) {
|
||||||
|
throw new MyException('Something just happend');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (MyException $e) {
|
||||||
|
// Handle my exception
|
||||||
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## More Information
|
## More Information
|
||||||
|
@ -473,9 +473,12 @@ add_10(3) # => 13
|
|||||||
|
|
||||||
# There are also anonymous functions
|
# There are also anonymous functions
|
||||||
(lambda x: x > 2)(3) # => True
|
(lambda x: x > 2)(3) # => True
|
||||||
|
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
|
||||||
|
|
||||||
# There are built-in higher order functions
|
# There are built-in higher order functions
|
||||||
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||||
|
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
|
||||||
|
|
||||||
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||||
|
|
||||||
# We can use list comprehensions for nice maps and filters
|
# We can use list comprehensions for nice maps and filters
|
||||||
|
@ -550,10 +550,13 @@ add_10(3) # => 13
|
|||||||
|
|
||||||
# There are also anonymous functions
|
# There are also anonymous functions
|
||||||
(lambda x: x > 2)(3) # => True
|
(lambda x: x > 2)(3) # => True
|
||||||
|
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
|
||||||
|
|
||||||
# TODO - Fix for iterables
|
# TODO - Fix for iterables
|
||||||
# There are built-in higher order functions
|
# There are built-in higher order functions
|
||||||
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||||
|
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
|
||||||
|
|
||||||
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||||
|
|
||||||
# We can use list comprehensions for nice maps and filters
|
# We can use list comprehensions for nice maps and filters
|
||||||
|
@ -106,8 +106,14 @@ placeholder = 'use string interpolation'
|
|||||||
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
|
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
|
||||||
'hello ' + 3.to_s #=> "hello 3"
|
'hello ' + 3.to_s #=> "hello 3"
|
||||||
|
|
||||||
# print to the output
|
# print to the output with a newline at the end
|
||||||
puts "I'm printing!"
|
puts "I'm printing!"
|
||||||
|
#=> I'm printing!
|
||||||
|
#=> nil
|
||||||
|
|
||||||
|
# print to the output without a newline
|
||||||
|
print "I'm printing!"
|
||||||
|
#=> I'm printing! => nill
|
||||||
|
|
||||||
# Variables
|
# Variables
|
||||||
x = 25 #=> 25
|
x = 25 #=> 25
|
||||||
@ -269,6 +275,19 @@ end
|
|||||||
#=> iteration 4
|
#=> iteration 4
|
||||||
#=> iteration 5
|
#=> iteration 5
|
||||||
|
|
||||||
|
# There are a bunch of other helpful looping functions in Ruby,
|
||||||
|
# for example "map", "reduce", "inject", the list goes on. Map,
|
||||||
|
# for instance, takes the array it's looping over, does something
|
||||||
|
# to it as defined in your block, and returns an entirely new array.
|
||||||
|
array = [1,2,3,4,5]
|
||||||
|
doubled = array.map do |element|
|
||||||
|
element * 2
|
||||||
|
end
|
||||||
|
puts doubled
|
||||||
|
#=> [2,4,6,8,10]
|
||||||
|
puts array
|
||||||
|
#=> [1,2,3,4,5]
|
||||||
|
|
||||||
grade = 'B'
|
grade = 'B'
|
||||||
|
|
||||||
case grade
|
case grade
|
||||||
|
@ -43,9 +43,13 @@ Scala - the scalable language
|
|||||||
// Printing, and forcing a new line on the next print
|
// Printing, and forcing a new line on the next print
|
||||||
println("Hello world!")
|
println("Hello world!")
|
||||||
println(10)
|
println(10)
|
||||||
|
// Hello world!
|
||||||
|
// 10
|
||||||
|
|
||||||
// Printing, without forcing a new line on next print
|
// Printing, without forcing a new line on next print
|
||||||
print("Hello world")
|
print("Hello world")
|
||||||
|
print(10)
|
||||||
|
// Hello world!10
|
||||||
|
|
||||||
// Declaring values is done using either var or val.
|
// Declaring values is done using either var or val.
|
||||||
// val declarations are immutable, whereas vars are mutable. Immutability is
|
// val declarations are immutable, whereas vars are mutable. Immutability is
|
||||||
|
@ -5,6 +5,7 @@ contributors:
|
|||||||
- ["Christopher Bess", "http://github.com/cbess"]
|
- ["Christopher Bess", "http://github.com/cbess"]
|
||||||
- ["Joey Huang", "http://github.com/kamidox"]
|
- ["Joey Huang", "http://github.com/kamidox"]
|
||||||
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
||||||
|
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||||
filename: learnswift.swift
|
filename: learnswift.swift
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -57,8 +58,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
|
|||||||
print("Build value: \(buildValue)") // Build value: 7
|
print("Build value: \(buildValue)") // Build value: 7
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Optionals are a Swift language feature that allows you to store a `Some` or
|
Optionals are a Swift language feature that either contains a value,
|
||||||
`None` value.
|
or contains nil (no value) to indicate that a value is missing.
|
||||||
|
A question mark (?) after the type marks the value as optional.
|
||||||
|
|
||||||
Because Swift requires every property to have a value, even nil must be
|
Because Swift requires every property to have a value, even nil must be
|
||||||
explicitly stored as an Optional value.
|
explicitly stored as an Optional value.
|
||||||
@ -79,6 +81,12 @@ if someOptionalString != nil {
|
|||||||
}
|
}
|
||||||
someOptionalString = nil
|
someOptionalString = nil
|
||||||
|
|
||||||
|
/*
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
|
||||||
// implicitly unwrapped optional
|
// implicitly unwrapped optional
|
||||||
var unwrappedString: String! = "Value is expected."
|
var unwrappedString: String! = "Value is expected."
|
||||||
// same as above, but ! is a postfix operator (more syntax candy)
|
// same as above, but ! is a postfix operator (more syntax candy)
|
||||||
@ -93,7 +101,7 @@ if let someOptionalStringConstant = someOptionalString {
|
|||||||
|
|
||||||
// Swift has support for storing a value of any type.
|
// Swift has support for storing a value of any type.
|
||||||
// AnyObject == id
|
// AnyObject == id
|
||||||
// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc)
|
// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.)
|
||||||
var anyObjectVar: AnyObject = 7
|
var anyObjectVar: AnyObject = 7
|
||||||
anyObjectVar = "Changed value to a string, not good practice, but possible."
|
anyObjectVar = "Changed value to a string, not good practice, but possible."
|
||||||
|
|
||||||
@ -295,7 +303,7 @@ print(numbers) // [3, 6, 18]
|
|||||||
// MARK: Structures
|
// MARK: Structures
|
||||||
//
|
//
|
||||||
|
|
||||||
// Structures and classes have very similar capabilites
|
// Structures and classes have very similar capabilities
|
||||||
struct NamesTable {
|
struct NamesTable {
|
||||||
let names = [String]()
|
let names = [String]()
|
||||||
|
|
||||||
@ -574,4 +582,18 @@ print(mySquare.sideLength) // 4
|
|||||||
// change side length using custom !!! operator, increases size by 3
|
// change side length using custom !!! operator, increases size by 3
|
||||||
!!!mySquare
|
!!!mySquare
|
||||||
print(mySquare.sideLength) // 12
|
print(mySquare.sideLength) // 12
|
||||||
|
|
||||||
|
// Operators can also be generics
|
||||||
|
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"
|
||||||
```
|
```
|
||||||
|
Loading…
x
Reference in New Issue
Block a user