├── .gitignore
├── 01_hello_world.playground
├── Contents.swift
└── contents.xcplayground
├── 02_var_let.playground
├── Contents.swift
└── contents.xcplayground
├── 03_numbers.playground
├── Contents.swift
└── contents.xcplayground
├── 04_data_types.playground
├── Contents.swift
└── contents.xcplayground
├── 05_errors.playground
├── Contents.swift
└── contents.xcplayground
├── 06_operations.playground
├── Contents.swift
└── contents.xcplayground
├── 07_strings.playground
├── Contents.swift
└── contents.xcplayground
├── 08_collections.playground
├── Contents.swift
└── contents.xcplayground
├── 09_control_flow.playground
├── Contents.swift
└── contents.xcplayground
├── 10_functions.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
├── 11_closures.playground
├── Contents.swift
└── contents.xcplayground
├── 12_enumerations.playground
├── Contents.swift
└── contents.xcplayground
├── 13_struct_class.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
├── 14_properties.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
├── 15_methods.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
├── 16_subscripts.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
├── 17_inheritance.playground
├── Contents.swift
└── contents.xcplayground
├── 18_inits.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
├── 19_optional_chaining.playground
├── Contents.swift
├── contents.xcplayground
└── timeline.xctimeline
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .DS_Store
3 |
--------------------------------------------------------------------------------
/01_hello_world.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | var str = "Hello, playground"
4 |
5 |
6 | print("Hola Mundo!")
7 |
--------------------------------------------------------------------------------
/01_hello_world.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/02_var_let.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | let maximumNumberOfLoginAttempts = 3
4 |
5 | var currentLoginAttempt = 0
6 |
7 | var x = 0.0, y = 0.0, z = 0.0
8 |
9 |
10 | var welcomeMessage : String
11 |
12 | welcomeMessage = "Hola, ¿que tal?"
13 |
14 | var red, green, blue : Double
15 |
16 |
17 | let π = 3.141592
18 | let 你好 : String
19 | var 👽 = "Alien"
20 |
21 | print(👽)
22 | 👽 = "Alien 2"
23 |
24 | print("El número de login actual es: \(currentLoginAttempt) de un total disponible de: \(maximumNumberOfLoginAttempts)")
25 |
26 | // Esto es un comentario
27 |
28 | /* Esto es un comentario
29 | Ocupa varias líneas
30 | Y puedo escribir muuucha cosa */
31 |
32 | /* Este es un comentario multilinea
33 | /* Este es un comentario anidado */
34 | Esto es otro comentario multilinea*/
35 |
--------------------------------------------------------------------------------
/02_var_let.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/03_numbers.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | let age : UInt8 = 31
4 |
5 | let minValue = UInt8.min //2^0-1
6 | let maxValue = UInt8.max //2^8-1
7 |
8 |
9 | let f1: Float = 3.14159265
10 | let d1: Double = 3.14159265
11 |
12 | let meaningOfLife = 42 //Int
13 | let pi = 3.14159 //Double
14 | let anotherPi = 3 + 0.14159 //Double
15 |
16 | let decimalInteger = 17 // 1*10^1 + 7*10^0
17 | let binaryInteger = 0b10001 //1*2^4+0*2^3+0*2^2+0*2^1+1*2^0
18 | let octalInteger = 0o21 //2*8^1+1*8^0
19 | let hexadecimalInteger = 0x11 //1*16^1+1*16^0
20 |
21 | let decimalDouble = 12.1875
22 | let exponentDouble = 1.21875e1
23 | let hexadecimalDouble = 0xC.3p0
24 |
25 | let paddedDouble = 000123.456
26 | let someNumber = 00000097.540
27 |
28 | let oneMillion = 1_000_000
29 | let justMoreThanAMillion = 1_000_000.000_000_1
30 |
31 | //ERRORES DE TIPO DE DATO
32 | //let cannotBeNegative: UInt8 = -1
33 | //let tooBig: UInt8 = UInt8.max + 1
34 |
35 | let twoThousand: UInt16 = 2_000
36 | let one: UInt8 = 1
37 | let twoThousandAndOne = twoThousand + UInt16(one)
38 |
39 | let three = 3
40 | let decimalNumber = 0.14159
41 | let piNum = Double(three) + decimalNumber
42 |
43 | let integerPi = Int(piNum)
44 |
45 | typealias AudioSample = UInt16
46 | var maxAmplitude = AudioSample.max // UInt16.max
47 |
--------------------------------------------------------------------------------
/03_numbers.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/04_data_types.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | let orangesAreOrange = true
4 | let foodIsDelicious = false
5 |
6 | var isAged : Bool
7 |
8 | isAged = true
9 |
10 | if isAged {//Solo entramos aquí, si isAged == true
11 | print("Puedes entrar en la fiesta")
12 | }else{//Solo entramos aquí, si isAged == false
13 | print("No puedes pasar a la fiesta")
14 | }
15 |
16 | var age = 12
17 | if age >= 18{
18 | print("Puedes entrar en la fiesta")
19 | }
20 |
21 |
22 | //TUPLAS
23 | let http404Error = (404, "Página no encontrada")
24 | let (statusCode, statusMessage) = http404Error
25 | print("El código del estado es \(statusCode)")
26 | print("El mensaje del servidor es \(statusMessage)")
27 |
28 | let (justStatusCode, _) = http404Error
29 | print("El código del estado es \(justStatusCode)")
30 |
31 | print("El código del error es \(http404Error.0) y el mensaje es \(http404Error.1)")
32 |
33 | let http200Status = (statusCode: 200, description: "OK")
34 | print("El código del estado es \(http200Status.statusCode) y el mensaje es \(http200Status.description)")
35 |
36 | let possibleAge = "31"
37 | let convertedAge = Int(possibleAge) //Int?
38 |
39 | var serverResponseCode: Int? = 404
40 | serverResponseCode = nil
41 |
42 | var surveyAnswer : String?
43 |
44 | surveyAnswer = "42"
45 |
46 |
47 | if convertedAge != nil {
48 | print("La edad del usuario no es nula: \(convertedAge!)")
49 | } else{
50 | print("La edad del usuario es nula")
51 | }
52 |
53 |
54 | if let actualAnswer = surveyAnswer {
55 | //Al llegar aquí, surveyAnswer != nil
56 | print("El string \(surveyAnswer) tiene el valor \(actualAnswer)")
57 | }else{
58 | //Al llegar aquí, surveyAnswer = nil
59 | print("El string \(surveyAnswer) es nil... ")
60 | }
61 |
62 |
63 | if let firstNumber = Int("4"),
64 | let secondNumber = Int("42"),
65 | firstNumber < secondNumber && secondNumber<100{
66 | print("\(firstNumber) < \(secondNumber) < 100")
67 | }
68 |
69 |
70 | if let firstNumber = Int("4"){
71 | if let secondNumber = Int("42"){
72 | if firstNumber < secondNumber && secondNumber<100 {
73 | print("\(firstNumber) < \(secondNumber) < 100")
74 | }
75 | }
76 | }
77 |
78 |
79 |
80 | let possibleString: String? = "Un string opcional"
81 | let forcedString: String = possibleString!
82 |
83 | let assummedString: String! = "Un string unwrapped de forma implicita a partir de un optional"
84 | let implicitString: String = assummedString
85 |
86 | if assummedString != nil {
87 | print(assummedString!)
88 | }
89 |
90 | if let definitiveString = assummedString {
91 | print(definitiveString)
92 | }
93 |
94 | print(assummedString)
95 |
--------------------------------------------------------------------------------
/04_data_types.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/05_errors.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | func canThrowError() throws{
4 | //aquí hay codigo que puede causar un error
5 | }
6 |
7 |
8 | do{
9 | try canThrowError()
10 | //si llegamos aquí, no ha habido error
11 | }catch{
12 | //si llegamos aquí, ha habido un error...
13 | }
14 |
15 |
16 | func makeASandwich() throws{
17 |
18 | }
19 |
20 | do{
21 | try makeASandwich()
22 | //Me como el sandwich
23 | }catch{
24 | //tengo platos limpios... -> Lavar los platos
25 | //tengo ingredientes -> Ir a hace la compra
26 | //no tengo hambre -> esperar dentro de una hora
27 | }
28 |
29 |
30 | // Aserciones (debug) y Preciondiciones (build)
31 |
32 | let age = -5
33 | //assert(age>=0, "La edad de una persona no puede ser negativa")
34 | precondition(age>=0, "La edad de una persona no puede ser negativa")
35 | //... aquí el código sigue
36 |
37 | if age > 10 {
38 | print("Puedes subir a la montaña rusa")
39 | }else if age >= 0{
40 | print("Eres demasiado pequeño para subir a la montaña rusa")
41 | }else{
42 | assertionFailure("La edad de una persona no puede ser negativa")
43 | }
44 |
--------------------------------------------------------------------------------
/05_errors.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/06_operations.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | let b = 10
4 | var a = 5
5 | a = b
6 |
7 | let (x,y) = (1,2)
8 |
9 | //let 2 = z
10 |
11 | if a == b {
12 | print("Los valores de a y b son iguales")
13 | }
14 |
15 | 1+2
16 | 5-3
17 | 2*3
18 | 10.0/2.5
19 |
20 | "Hello " + "World"
21 |
22 | //D/d -> D == d*c+r
23 | 9/4 //c
24 | 9%4 //r
25 |
26 | 9 == 4*2+1
27 |
28 |
29 | -9%4 // -9 == -2*4 + (-1)
30 |
31 | let five = 5
32 | let minusFive = -five
33 | let plusFive = -minusFive
34 |
35 | let minusSix = -6
36 | let alsoMinusSix = +minusSix
37 |
38 | var number = 5
39 | number += 3 //number = number + 3
40 | number -= 2 //number = number - 2
41 |
42 | 1 == 1
43 | 1 == 2
44 | 1 != 2
45 | 2 > 1
46 | 2 < 1
47 | 2 >= 1
48 | 1 >= 1
49 | 2 <= 1
50 |
51 | let name = "Ricardo Celis"
52 |
53 | if name == "Juan Gabriel" {
54 | print("Bienvenido \(name), eres invitado a la fiesta")
55 | }else{
56 | print("Cuidado, ha aparecido un \(name) salvaje")
57 | }
58 |
59 |
60 | (1, "Juan Gabriel") < (2, "Ricardo Celis")
61 | (3, "Juan Gabriel") < (3, "Ricardo Celis")
62 | (3, "Ricardo") < (3, "Juan Gabriel")
63 | (4, "perro") == (4, "perro")
64 |
65 | ("perro", false) == ("perro", true)
66 |
67 | /*
68 | if question {
69 | answer1
70 | } else{
71 | answer2
72 | }
73 | */
74 |
75 |
76 |
77 |
78 | let contentHeight = 40
79 | var hasImage = true
80 | var rowHeight = 0
81 |
82 | rowHeight = contentHeight + (hasImage ? 50 : 10)
83 |
84 |
85 |
86 |
87 | let defaultAge = 18
88 | var userAge: Int?
89 |
90 | userAge = 31
91 |
92 | var ageToBeUsed = userAge ?? defaultAge
93 | // ageToBeUsed = (userAge != nil ? userAge! : defaultAge)
94 |
95 | let defaultColorName = "red"
96 | var userColorName: String? = "green"
97 |
98 | var colorNameToUse = userColorName ?? defaultColorName
99 |
100 | for idx in 1...5 {
101 | print(idx)
102 | }
103 |
104 | for idx in 1..<5{
105 | print(idx)
106 | }
107 |
108 | let names = ["Ricardo", "Juan Gabriel", "Pedro"]
109 | for i in 0..
2 |
3 |
4 |
--------------------------------------------------------------------------------
/07_strings.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | let someString = "Soy un string cualquiera"
4 |
5 | let multiLineString = """
6 | Soy Juan Gabriel Gomila\
7 | Estamos haciendo el curso de Swift\
8 | Un saludo, paz y amor...
9 | """
10 |
11 | print(multiLineString)
12 |
13 |
14 | let wiseWords = "\"La imaginación es más importante que el saber\" - Albert Einstein"
15 | let dolarSign = "\u{24}"
16 | let blackHeart = "\u{2665}"
17 | let heart = "\u{1F496}"
18 |
19 |
20 | var emptyString = ""
21 | var anotherEmptyString = String()
22 |
23 | if emptyString.isEmpty {
24 | print("Nada que ver aquí")
25 | } else{
26 | print("El string tiene un valor")
27 | }
28 |
29 | var newSomeString = "Un caballo"
30 | newSomeString += " y un carruaje"
31 | newSomeString += " y un soldado"
32 |
33 | let aString = "Juan Gabriel"
34 | //aString += " y Ricardo Celis"
35 |
36 | var a = "A"
37 | var b = "B"
38 | print("a vale \(a) y b vale \(b) ")
39 | b = a
40 | print("a vale \(a) y b vale \(b) ")
41 | b = "C"
42 | print("a vale \(a) y b vale \(b) ")
43 | a = "D"
44 | print("a vale \(a) y b vale \(b) ")
45 |
46 |
47 | let name = "Juan Gabriel 😎"
48 | for ch in name {
49 | print(ch)
50 | }
51 | print(name.count)
52 |
53 | let exclamationMark : Character = "!"
54 |
55 | let nameChars: [Character] = ["J", "u", "a", "n"]
56 | var nameString = String(nameChars)
57 |
58 | let compoundName = "Juan " + "Gabriel"
59 |
60 | nameString.append(exclamationMark)
61 |
62 | let multiplier = 3
63 | var message = "El producto de \(multiplier) x 3.5 da \(Double(multiplier)*3.5)"
64 | message.append(exclamationMark)
65 |
66 | let greeting = "Hola, ¿que tal?"
67 | greeting[greeting.startIndex]
68 | //greeting[greeting.endIndex]
69 | greeting[greeting.index(before: greeting.endIndex)]
70 | greeting[greeting.index(after: greeting.startIndex)]
71 |
72 | for idx in greeting.indices{
73 | print("\(greeting[idx])", terminator:"")
74 | }
75 |
76 |
77 | var welcome = "Hola"
78 |
79 | welcome.insert("!", at: welcome.endIndex)
80 | welcome.insert(contentsOf: " que tal",
81 | at: welcome.index(before: welcome.endIndex))
82 |
83 | welcome.remove(at: welcome.index(before: welcome.endIndex))
84 | welcome
85 | let range = welcome.index(welcome.endIndex, offsetBy: -7)..
2 |
3 |
4 |
--------------------------------------------------------------------------------
/08_collections.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | //Array
4 | //Conjuntos
5 | //Diccionarios
6 |
7 |
8 | //ARRAY
9 | var someInts = [Int]()
10 | someInts.count
11 | someInts.append(31)
12 | someInts.count
13 | someInts = []
14 | someInts.count
15 |
16 |
17 | var someDoubles = Array(repeating: 3.141592, count: 3)
18 | someDoubles.count
19 |
20 | var moreDoubles = Array(repeating: 2.5, count: 4)
21 |
22 | var aLotOfDoubles = someDoubles + moreDoubles
23 | aLotOfDoubles.count
24 |
25 | var shoppingList : [String] = ["Papas", "Pimiento", "Tortillas", "Cerdo", "Cebolla"]
26 | shoppingList.count
27 |
28 |
29 | if shoppingList.isEmpty {
30 | print("La lista de la compra está vacía")
31 | } else{
32 | print("Mandemos a Ricardo a comprar")
33 | }
34 |
35 | shoppingList.append("Coca Cola")
36 | shoppingList.count
37 |
38 | shoppingList += ["Totopos", "Guacamole", "Pico de Gallo"]
39 | shoppingList.count
40 |
41 | var firstElement = shoppingList[0]
42 | shoppingList[0] = "Huevos"
43 | shoppingList
44 | shoppingList[5]
45 | shoppingList[4...6]
46 | shoppingList[4...6] = ["Naranja", "Plátano", "Mango"]
47 | shoppingList
48 |
49 | let pepper = shoppingList.remove(at: 1)
50 | shoppingList
51 |
52 | let _ = shoppingList.removeLast()
53 | shoppingList
54 |
55 | for item in shoppingList{
56 | print(item)
57 | }
58 |
59 | for (idx, item) in shoppingList.enumerated(){
60 | print("Item \(idx+1): \(item) ")
61 | }
62 |
63 |
64 |
65 | //Conjunto (Set)
66 | var letters = Set()
67 | letters.count
68 | letters.insert("a")
69 | letters.insert("h")
70 | letters.insert("b")
71 | letters
72 |
73 |
74 | var favouriteGames : Set = ["Final Fantasy", "World of Warcraft", "Farcry"]
75 | favouriteGames.count
76 |
77 |
78 | if favouriteGames.isEmpty{
79 | print("No hay juegos favoritos")
80 | }
81 |
82 | favouriteGames.insert("Metal Gear")
83 |
84 | if let removedGame = favouriteGames.remove("Farcry"){
85 | print("He eliminado de la lista \(removedGame)")
86 | }
87 |
88 | if favouriteGames.contains("Metal Gear"){
89 | print("Me encanta ese juego")
90 | }
91 |
92 | for vg in favouriteGames.sorted() {
93 | print(vg)
94 | }
95 |
96 | let oddDigits: Set = [1,3,5,7,9]
97 | let evenDigits: Set = [0,2,4,6,8]
98 | let primeNumbers: Set = [2,3,5,7]
99 |
100 | //A union B = elementos que son o bien de A, o bien de B o de los dos
101 | oddDigits.union(evenDigits).sorted()
102 | //A intersección B = elementos que son a la vez de A y de B
103 | oddDigits.intersection(evenDigits)
104 | evenDigits.intersection(primeNumbers).sorted()
105 | oddDigits.intersection(primeNumbers).sorted()
106 |
107 | // A - B = elementos que son de A pero no de B
108 | oddDigits.subtracting(primeNumbers).sorted()
109 |
110 | // A + B = (A-B) union (B-A)
111 | oddDigits.symmetricDifference(primeNumbers).sorted()
112 |
113 |
114 | let houseAnimals:Set = ["🐶", "😹"]
115 | let farmAnimals:Set = ["🐮", "🐔", "🐑", "🐶", "😹"]
116 | let cityAnimals:Set = ["🐁", "🕊"]
117 |
118 | houseAnimals.isSubset(of: farmAnimals)
119 | farmAnimals.isSuperset(of: houseAnimals)
120 | //A y B son disjuntos si su intersección es vacía
121 | farmAnimals.isDisjoint(with: cityAnimals)
122 |
123 |
124 |
125 | // Diccionarios [k1:v1, k2:v2, ....]
126 |
127 | var namesOfIntegers = [Int : String]()
128 | namesOfIntegers[15] = "quince"
129 | namesOfIntegers = [:]
130 |
131 | var airports: [String: String] = ["YYZ": "Toronto",
132 | "DUB": "Dublin",
133 | "PMI": "Palma de Mallorca"]
134 |
135 | airports.count
136 |
137 | airports.isEmpty
138 | airports["LHR"] = "London City Airport"
139 | airports
140 | airports["LHR"] = "London Heathrow"
141 | airports
142 |
143 | if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB"){
144 | print("El aeropuerto tenia antiguamente el nombre de \(oldValue)")
145 | }
146 | airports
147 |
148 | if let airportName = airports["DUB"]{
149 | print("El aeropuerto de DUB es: \(airportName)")
150 | }
151 |
152 | airports["PMI"] = nil
153 | airports
154 |
155 | if let removedAirport = airports.removeValue(forKey: "DUB"){
156 | //usar la variable removed airport
157 | }
158 | airports
159 |
160 | for (key, value) in airports {
161 | print("\(key) - \(value)")
162 | }
163 |
164 | for airportKey in airports.keys{
165 | print(airportKey)
166 | }
167 |
168 | for airportName in airports.values{
169 | print(airportName)
170 | }
171 |
172 | let airportKeys = [String](airports.keys.sorted())
173 | let airportNames = [String](airports.values.sorted())
174 |
--------------------------------------------------------------------------------
/08_collections.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/09_control_flow.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | //Bucle for-in
4 |
5 | let names = ["Ricardo Celis", "Juan Gabriel", "Edgar"]
6 |
7 | for name in names {
8 | print("Hola \(name)")
9 | }
10 |
11 | let numberOfLegs = ["spider": 8, "ant": 6, "dog":4]
12 |
13 | for (animalName, legCount) in numberOfLegs{
14 | print("Animal: \(animalName), número de patas: \(legCount)")
15 | }
16 |
17 | for idx in 1...5{
18 | print("\(idx) x 3 = \(idx*3)")
19 | }
20 |
21 | let base = 2
22 | let power = 10
23 | var answer = 1
24 |
25 | for _ in 0..= 25{//temp > 25
56 | print("Hace calor! Encendamos el aire acondicionado")
57 | }else{// 15 < temp < 25
58 | print("La sensación térmica es agradable. No hace falta modificarla")
59 | }
60 |
61 |
62 | //Switch/Case
63 |
64 | let someCharacter: Character = "Z"
65 | switch someCharacter {
66 | case "a", "A":
67 | print("Es la primera letra del alfabeto")
68 | case "z", "Z":
69 | print("Es la última letra del alfabeto")
70 | default:
71 | print("Es alguna otra letra")
72 | }
73 |
74 |
75 | let moons = 62
76 | let phrase = "lunas en Saturno"
77 | let naturalCount : String
78 | switch moons {
79 | case 0:
80 | naturalCount = "No hay"
81 | case 1, 2, 3, 4:
82 | naturalCount = "Hay unas pocas"
83 | case 5..<12:
84 | naturalCount = "Hay bastantes"
85 | case 12..<100:
86 | naturalCount = "Hay decenas de"
87 | case 100..<1000:
88 | naturalCount = "Hay centenares de"
89 | default:
90 | naturalCount = "Hay muchiiiiisimas"
91 | }
92 | print("\(naturalCount) \(phrase)")
93 |
94 |
95 | let somePoint = (5,-8)
96 | switch somePoint {
97 | case (0,0):
98 | print("El punto \(somePoint) es el origen de coordenadas")
99 | case (_, 0):
100 | print("El punto \(somePoint) se halla sobre el eje de las X")
101 | case (0, _):
102 | print("El punto \(somePoint) se halla sobre el eje de las Y")
103 | case (-2...2, -2...2):
104 | print("El punto \(somePoint) se halla en el interior del cuadrado de lado 4")
105 | default:
106 | print("El punto \(somePoint) está en algún otro lado")
107 | }
108 |
109 |
110 | let anotherPoint = (5,-2)
111 | switch anotherPoint {
112 | case (let x, 0):
113 | print("Sobre el eje de las X, con valor \(x)")
114 | case (0, let y):
115 | print("Sobre el eje de las Y, con valor \(y)")
116 | case let (x,y) where x == y:
117 | print("El punto se halla sobre la recta x = y")
118 | case let (x,y) where x == -y:
119 | print("El punto se halla sobre la recta x = -y")
120 | case let (x,y):
121 | print("En algún otro lugar del plano, en (\(x), \(y))")
122 | }
123 |
124 | let anotherCharacter: Character = " "
125 | switch anotherCharacter {
126 | case "a", "e", "i", "o", "u":
127 | print("Se trata de una vocal")
128 | case "b", "c", "d", "f", "g"://TODO: acabar con el resto del abecedario (solo consonantes)
129 | print("Se trata de una consonante")
130 | default:
131 | print("Se trata de un caracter no vocal ni consonante (minúscula)")
132 | }
133 |
134 | let stillAnotherPoint = (0,5)
135 | switch stillAnotherPoint {
136 | case (let distance, 0), (0, let distance):
137 | print("Se halla sobre el eje, a distancia \(distance) del origen")
138 | default:
139 | break
140 | }
141 |
142 |
143 | //Control Transfer Sentences - continue, break, fallthrough, return, throw
144 |
145 | let sentence = "las mentes grandes piensan igual"
146 | var filteredSentence = ""
147 | let charactersToRemove:[Character] = ["a", "e", "i", "o", "u"]
148 | for ch in sentence{
149 | if charactersToRemove.contains(ch){
150 | continue
151 | }
152 | filteredSentence.append(ch)
153 | if ch == "d"{
154 | break
155 | }
156 | }
157 | filteredSentence
158 |
159 |
160 | let integerToDescribe = 5
161 | var description = "El número \(integerToDescribe) es"
162 | switch integerToDescribe {
163 | case 2,3,5,7,11,13,17,19:
164 | description += " un número primo, y"
165 | fallthrough
166 | default:
167 | description += " un número entero."
168 | }
169 | print(description)
170 |
171 | var people = ["name": "Juan Gabriel", "age": 31, "isMale": true] as [String : Any]
172 |
173 | func testUserValidation(person:[String: Any]){
174 | guard let surname = person["surname"] else{
175 | print("El apellido es desconocido")
176 | return
177 | }
178 | //aquí existe surname
179 | print(surname)
180 | guard let age = person["age"] else{
181 | print("La edad es desconocida")
182 | return
183 | }
184 | print("La edad de la persona es \(age)")
185 | }
186 |
187 | people["surname"] = "Gomila"
188 | testUserValidation(person: people)
189 |
190 | if #available(iOS 12, macOS 10.12, *){
191 | //Ejecutar las acciones a lo iOS12+, a los macOS12+
192 | }else{
193 | //Mantener el código viejo con versiones anteriores de iOS, macOS...
194 | }
195 |
--------------------------------------------------------------------------------
/09_control_flow.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/10_functions.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | func greeting(person: String) -> String {
4 | let greet = "¡Bienvenue, \(person)!"
5 | return greet
6 | }
7 |
8 | greeting(person: "Ricardo Celis")
9 | greeting(person: "Edgar")
10 | greeting(person: "Juan Gabriel")
11 |
12 |
13 | func sayHelloWorld() -> String {
14 | return "Hello World"
15 | }
16 |
17 | sayHelloWorld()
18 | sayHelloWorld()
19 | sayHelloWorld()
20 |
21 | func greeting(person: String, isMale:Bool) -> String {
22 | if isMale {
23 | return "Bienvenido Caballero \(person)"
24 | }else{
25 | return "Bienvenida Señorita \(person)"
26 | }
27 | }
28 | greeting(person: "RicardoCelis", isMale: true)
29 | greeting(person: "Olivia", isMale: false)
30 |
31 |
32 | func greet2(person:String){
33 | print("Hola \(person)")
34 | }
35 | greet2(person: "Ricardo Celis")
36 | greet2(person: "Edgar")
37 |
38 | func printAndCount(string : String) -> Int{
39 | print(string)
40 | return string.count
41 | }
42 |
43 | func printWithoutCounting(string: String){
44 | let _ = printAndCount(string: string)
45 | }
46 |
47 | printAndCount(string: "Hola que tal")
48 | printWithoutCounting(string: "Hola que tal")
49 |
50 |
51 | func minMax(array:[Int]) -> (min: Int, max: Int)?{
52 |
53 | if array.isEmpty { return nil }
54 |
55 | var currentMin = array[0]
56 | var currentMax = array[0]
57 |
58 | for value in array[1.. currentMax{
62 | currentMax = value
63 | }
64 | }
65 |
66 | return (currentMin, currentMax)
67 | }
68 |
69 | let bounds = minMax(array: [6,3,-8,3,1,9,5,15,-9])
70 | print("Los valores se halla entre \(bounds!.min) y \(bounds!.max)")
71 |
72 | minMax(array: [])
73 |
74 |
75 |
76 | func someFunction(f1 firstParamName: Int, f2 secondParamName:Int = 6){
77 | //firstParamName variable de tipo Int
78 | //secondParamName variable de tipo Int
79 | print(firstParamName + secondParamName)
80 | }
81 | someFunction(f1: 5, f2: 1)
82 | someFunction(f1: 5)
83 | func greeting(_ person: String,from hometown: String) -> String {
84 | return "Hola \(person) un placer que no visites desde \(hometown)"
85 | }
86 | greeting("Juan Gabriel", from: "Mallorca")
87 |
88 |
89 |
90 | func mean(_ numbers: Double...) -> Double {
91 | var total : Double = 0
92 | for number in numbers{
93 | total += number
94 | }
95 | return total / Double(numbers.count)
96 | }
97 | mean(1,2,3,4,5)
98 | mean(1.5, 2.7)
99 | mean(3, 4.5, 18.75)
100 |
101 | let x = 5
102 | func addOne(number: Int) {
103 | var number2 = number
104 | number2 += 1
105 | print("El número ahora vale \(number2)")
106 | }
107 | addOne(number: x)
108 |
109 |
110 |
111 | func swapTwoInts(_ a: inout Int,_ b: inout Int){
112 | let tempA = a
113 | a = b
114 | b = tempA
115 | }
116 |
117 | var someInt = 3
118 | var otherInt = 7
119 | print("someInt vale \(someInt) y otherInt vale \(otherInt)")
120 | swapTwoInts(&someInt, &otherInt)
121 | print("someInt vale \(someInt) y otherInt vale \(otherInt)")
122 |
123 | func addTwoInts(_ a: Int, _ b: Int) -> Int {
124 | return a+b
125 | } //(Int, Int) -> Int
126 |
127 | func multiplyTwoInts(_ a: Int, _ b: Int ) -> Int{
128 | return a*b
129 | }//(Int, Int) -> Int
130 |
131 | func printHW(){
132 | print("Hello World")
133 | } //() -> Void
134 |
135 | var mathFunction: (Int, Int) -> Int = multiplyTwoInts
136 | mathFunction(4,5)
137 |
138 |
139 |
140 | func printMathResult(_ mathFunc: (Int, Int) -> Int, _ a: Int, _ b: Int){
141 | print("Resultado: \(mathFunction(a,b))")
142 | }
143 |
144 | printMathResult(multiplyTwoInts, 5, 9)
145 |
146 |
147 |
148 |
149 | func chooseStepFunction(backward: Bool ) -> (Int) -> Int {
150 |
151 | func stepForward(_ input: Int) -> Int {
152 | return input + 1
153 | }
154 |
155 | func stepBackward(_ input: Int) -> Int {
156 | return input - 1
157 | }
158 |
159 | return backward ? stepBackward : stepForward
160 | }
161 |
162 | var value = -7
163 | let moveNearerZero = chooseStepFunction(backward: value > 0)
164 | while value != 0{
165 | print("\(value)...")
166 | value = moveNearerZero(value)
167 | }
168 | print("Cero!!!!!!")
169 |
170 |
--------------------------------------------------------------------------------
/10_functions.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/10_functions.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/11_closures.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | //1. Global functions
4 | //2. Nested functions
5 | //3. Closure
6 |
7 | let names = ["Christian", "Ricardo", "Juan Gabriel", "Edgar", "Freddy"]
8 |
9 | func backward(_ s1: String, _ s2: String) -> Bool {
10 | return s1 > s2
11 | }
12 | backward("Juan Gabriel", "Edgar")
13 |
14 | var reversedNames = names.sorted(by: backward)
15 |
16 | /*
17 | { (params) -> return type in
18 | //Código del closure
19 | }
20 | */
21 |
22 | reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in return s1>s2 })
23 | reversedNames = names.sorted(by: { s1, s2 in return s1>s2 })
24 | reversedNames = names.sorted(by: { s1, s2 in s1>s2 })
25 | reversedNames = names.sorted(by: { $0>$1 })
26 | reversedNames = names.sorted(by: >)
27 |
28 |
29 | func someFunctionThatTakesAClosure(closure: () -> Void){
30 | //Aquí iria el cuerpo de la función
31 | }
32 |
33 | someFunctionThatTakesAClosure (closure: {
34 | //Aquí iria el cuerpo del closure
35 | })
36 |
37 | someFunctionThatTakesAClosure {
38 | //Añadir el closure aquí
39 | }
40 |
41 | reversedNames = names.sorted {$0>$1}
42 |
43 | let digitNames = [0:"Cero", 1:"Uno", 2:"Dos", 3:"Tres", 4:"Cuatro",
44 | 5:"Cinco", 6:"Seis", 7:"Siete", 8:"Ocho", 9:"Nueve"]
45 | let numbers = [16, 58, 510, 2127]
46 |
47 | let numberStrings = numbers.map { (number) -> String in
48 |
49 | var number = number
50 | var output = ""
51 | repeat{
52 | output = digitNames[number%10]! + output
53 | number /= 10
54 | }while number > 0
55 | return output
56 | }
57 |
58 |
59 | func makeIncrementer(forIncrement amount: Int) -> () -> Int {
60 | var runningTotal = 0
61 | func incrementer() -> Int {
62 | runningTotal += amount
63 | return runningTotal
64 | }
65 | return incrementer
66 | }
67 |
68 | let incrementByTen = makeIncrementer(forIncrement: 10)
69 | incrementByTen()
70 | incrementByTen()
71 | incrementByTen()
72 |
73 | let incrementBySeven = makeIncrementer(forIncrement: 7)
74 | incrementBySeven()
75 |
76 | incrementByTen()
77 |
78 |
79 | var completionHandlers: [() -> Void] = []
80 |
81 | func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void){
82 | completionHandlers.append(completionHandler)
83 | }
84 | completionHandlers.count
85 |
86 | func someFunctionWithNonEscapingClosure(closure: () -> Void){
87 | closure()
88 | }
89 |
90 |
91 | class SomeClass{
92 | var x = 10
93 | func doSomething(){
94 | someFunctionWithEscapingClosure {
95 | self.x = 100
96 | }
97 | someFunctionWithNonEscapingClosure {
98 | x = 200
99 | }
100 | }
101 | }
102 |
103 | let instance = SomeClass()
104 | print(instance.x)
105 |
106 | instance.doSomething()
107 | print(instance.x)
108 |
109 | completionHandlers.count
110 | completionHandlers.first?()
111 | print(instance.x)
112 |
--------------------------------------------------------------------------------
/11_closures.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/12_enumerations.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | enum SomeEnumeration{
4 | //aquí iria la definición del enumerado
5 | }
6 |
7 | enum CompassPoint: String {
8 | case north
9 | case south
10 | case east
11 | case west
12 | }
13 |
14 | enum Planet: Int{
15 | case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
16 | }
17 |
18 | var directionToGo = CompassPoint.east
19 | directionToGo = .south
20 |
21 | switch directionToGo {
22 | case .north:
23 | print("Hay que ir al norte")
24 | case .south:
25 | print("Hay pinguinos en el sur")
26 | case .east:
27 | print("Mordor se extiende hacia las tierras del este")
28 | case .west:
29 | print("Cuidado con los vaqueros")
30 | }
31 |
32 | let somePlanet = Planet.mars
33 | switch somePlanet {
34 | case .earth:
35 | print("La tierra es segura")
36 | default:
37 | print("No es seguro ir a este planeta")
38 | }
39 |
40 | enum Beverage: CaseIterable {
41 | case coffee, tea, juice, redbull
42 | }
43 | let numberOfChoices = Beverage.allCases.count
44 | for beverage in Beverage.allCases{
45 | print(beverage)
46 | }
47 |
48 | enum Barcode{
49 | case upc(Int, Int, Int, Int)
50 | case qrCode(String)
51 | }
52 |
53 | var productBarcode = Barcode.upc(8, 85909, 51226, 3)
54 | productBarcode = .qrCode("ASDFGHJKL")
55 |
56 | switch productBarcode {
57 | case let .upc(numberSystem, manufacturer, product, check):
58 | print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
59 | case let .qrCode(productCode):
60 | print("QR: \(productCode)")
61 | }
62 |
63 | enum ASCIIControlCharacter: Character{
64 | case tab = "\t"
65 | case lineFeed = "\n"
66 | case carriageReturn = "\r"
67 | }
68 |
69 |
70 |
71 | let earthOrder = Planet.earth.rawValue
72 |
73 | let northDirection = CompassPoint.north.rawValue
74 |
75 | let possiblePlanet = Planet(rawValue: 5)
76 |
77 | let planetPosition = 3
78 | if let anyPlanet = Planet(rawValue: planetPosition){
79 | switch anyPlanet{
80 | case .earth:
81 | print("La tierra es segura")
82 | default:
83 | print("No es seguro ir a este planeta")
84 | }
85 | }else{
86 | print("El planeta indicado no existe... ")
87 | }
88 |
--------------------------------------------------------------------------------
/12_enumerations.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/13_struct_class.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | //Struct vs Class
4 |
5 | struct SomeStruct {
6 | //La definición de la estructura aquí
7 | }
8 | class SomeClass {
9 | //La definición de la clase aquí
10 | }
11 |
12 | struct Resolution {
13 | var width = 0
14 | var height = 0
15 | }
16 |
17 | class VideoMode {
18 | var resolution = Resolution()
19 | var interlaced = false
20 | var frameRate = 0.0
21 | var name: String?
22 | }
23 |
24 | let someResolution = Resolution()
25 | let someVideoMode = VideoMode()
26 |
27 | print(someResolution.width)
28 | someVideoMode.resolution.width = 1280
29 | print(someVideoMode.resolution.width)
30 |
31 | someVideoMode.frameRate = 30.0
32 | print(someVideoMode.frameRate)
33 |
34 | let vga = Resolution(width: 640, height: 480)
35 | vga.width
36 | vga.height
37 |
38 | let hd = Resolution(width: 1920, height: 1080)
39 |
40 | var cinema = hd
41 | print("\(cinema.width) x \(cinema.height)")
42 | cinema.width = 2048
43 | print("\(cinema.width) x \(cinema.height)")
44 | print("\(hd.width) x \(hd.height)")
45 |
46 |
47 | enum CompassPoint{
48 | case north, south, east, west
49 | }
50 |
51 | var currentDirection = CompassPoint.north
52 | var oldDirection = currentDirection
53 | currentDirection = .south
54 |
55 | print(currentDirection)
56 | print(oldDirection)
57 |
58 |
59 | let tenEighty = VideoMode()
60 | tenEighty.resolution = hd
61 | tenEighty.interlaced = true
62 | tenEighty.name = "1080i"
63 | tenEighty.frameRate = 25.0
64 |
65 | let alsoTenEighty = tenEighty
66 | alsoTenEighty.frameRate = 30.0
67 | tenEighty
68 |
69 |
70 | if tenEighty === alsoTenEighty{ //!==
71 | print("Son el mismo objeto")
72 | }else{
73 | print("Son diferentes")
74 | }
75 |
--------------------------------------------------------------------------------
/13_struct_class.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/13_struct_class.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
14 |
15 |
19 |
20 |
24 |
25 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/14_properties.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | struct FixedLengthRange {
4 | var firstValue : Int
5 | let length : Int
6 | }
7 |
8 | var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)
9 | rangeOfThreeItems.firstValue = 6
10 |
11 | let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)
12 | //rangeOfFourItems.firstValue = 5 ESTO DA ERROR...
13 |
14 | class DataImporter{
15 | var filename = "data.txt"
16 | }
17 |
18 | class DataManager {
19 | lazy var importer = DataImporter()
20 | var data = [String]()
21 | }
22 |
23 | let manager = DataManager()
24 | manager.data.append("Algo de datos")
25 | manager.data.append("Muchos más datos")
26 | manager
27 | //HAsta esta línea, el importer no ha sido creado...
28 | manager.importer.filename
29 | //Aquí, la variable importer ya ha sido creada
30 | manager
31 |
32 |
33 |
34 | struct Point {
35 | var x = 0.0, y = 0.0
36 | }
37 |
38 | struct Size {
39 | var width = 0.0, height = 0.0
40 | }
41 |
42 | struct Rect {
43 | var origin = Point()
44 | var size = Size()
45 | var center: Point{
46 | get{
47 | Point(x: origin.x + size.width/2, y: origin.y + size.height/2)
48 | }
49 | set{
50 | origin.x = newValue.x - size.width/2
51 | origin.y = newValue.y - size.height/2
52 | }
53 | }
54 | }
55 |
56 | var square = Rect(origin: Point(x: 0, y: 0), size: Size(width: 10, height: 10))
57 | square.center
58 | let initialSquareCenter = square.center
59 | square.center = Point(x: 18, y: 3)
60 |
61 | struct Cuboid{
62 | var width = 0.0, height = 0.0, depth = 0.0
63 | var volume: Double{
64 | return width * height * depth
65 | }
66 | }
67 |
68 | let cuboid = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
69 | cuboid.volume
70 | //cuboid.volume = 57.0 error, puesto que la variable es de solo lectura
71 |
72 |
73 | //willSet // didSet
74 |
75 | class StepCounter{
76 | var totalSteps: Int = 0{
77 | willSet(newTotalSteps){
78 | print("El número de pasos va a subir hasta \(newTotalSteps)")
79 | }
80 | didSet{
81 | if totalSteps > oldValue{
82 | print("El número de pasos ha incrementado en \(totalSteps - oldValue)")
83 | }
84 | }
85 | }
86 | }
87 |
88 | let stepCounter = StepCounter()
89 | stepCounter.totalSteps = 200
90 |
91 | stepCounter.totalSteps = 520
92 |
93 | stepCounter.totalSteps += 1234
94 |
95 |
96 | struct SomeStruct {
97 | var counter = 0
98 | static var storedTypeProperty = "SOME VALUE"
99 | static var computedTypeProperty: Int {
100 | return 1
101 | }
102 | }
103 |
104 | var instanceStr = SomeStruct()
105 |
106 | var otherInstanceStr = SomeStruct()
107 |
108 | SomeStruct.computedTypeProperty
109 |
110 | enum SomeEnum{
111 | static var storedTypeProperty = "SomeValue"
112 | static var computedTypeProperty: Int{
113 | return 5
114 | }
115 | }
116 |
117 | SomeEnum.storedTypeProperty
118 |
119 | class SomeClass{
120 | static var storedTypeProperty = "Some Value"
121 | static var computedTypeProperty:Int{
122 | return -9
123 | }
124 |
125 | class var overrideableComputedTypeProperty:Int{
126 | return 108
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/14_properties.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/14_properties.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
14 |
15 |
19 |
20 |
24 |
25 |
29 |
30 |
34 |
35 |
39 |
40 |
44 |
45 |
49 |
50 |
54 |
55 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/15_methods.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | class Counter {
4 | var count = 0
5 |
6 | func increment(){
7 | self.count += 1
8 | }
9 |
10 | func increment(by amount:Int) {
11 | self.count += amount
12 | }
13 |
14 | func reset(){
15 | self.count = 0
16 | }
17 | }
18 |
19 | let counter = Counter()
20 | counter.increment()
21 | counter.increment(by: 8)
22 | counter.reset()
23 |
24 |
25 | struct Point{
26 | var x = 0.0, y = 0.0
27 | func isToTheRight(of x:Double) -> Bool {
28 | return self.x > x
29 | }
30 |
31 | mutating func moveBy(x deltaX:Double, y deltaY: Double) {
32 | //self.x += deltaX
33 | //self.y += deltaY
34 | self = Point(x: self.x + deltaX, y: self.y + deltaY)
35 | }
36 | }
37 |
38 | var somePoint = Point(x: 4, y: 5)
39 | somePoint.isToTheRight(of: 1)
40 | somePoint.isToTheRight(of: 54)
41 |
42 | somePoint.moveBy(x: 2, y: -3)
43 | somePoint.x = 9
44 |
45 |
46 | enum DifferentStateSwitch{
47 | case off, low, high
48 | mutating func next(){
49 | switch self {
50 | case .off:
51 | self = .low
52 | case .low:
53 | self = .high
54 | case .high:
55 | self = .off
56 | }
57 | }
58 | }
59 |
60 | var controllerStatus = DifferentStateSwitch.off
61 | controllerStatus.next()
62 | controllerStatus.next()
63 | controllerStatus.next()
64 |
65 |
66 | class SomeClass{
67 | class func someMethod(){
68 | print("HOLA")
69 | }
70 | }
71 |
72 | SomeClass.someMethod()
73 |
74 |
75 | struct LevelTracker{
76 | static var highestUnlockedLevel = 1
77 | var currentLevel = 1
78 |
79 | static func unlock(_ level:Int){
80 | if level > highestUnlockedLevel{
81 | highestUnlockedLevel = level
82 | }
83 | }
84 |
85 | static func isUnlocked(_ level: Int) -> Bool{
86 | return level <= highestUnlockedLevel
87 | }
88 |
89 | mutating func advance(to level:Int) -> Bool {
90 | if LevelTracker.isUnlocked(level){
91 | currentLevel = level
92 | return true
93 | }else{
94 | return false
95 | }
96 | }
97 |
98 | }
99 |
100 |
101 | class Player{
102 | var tracker = LevelTracker()
103 | let playerName:String
104 | func complete(level: Int){
105 | LevelTracker.unlock(level + 1)
106 | tracker.advance(to: level + 1)
107 | }
108 |
109 | init(name: String) {
110 | self.playerName = name
111 | }
112 | }
113 |
114 |
115 | var player = Player(name: "Juan Gabriel")
116 | player.complete(level: 1)
117 | player
118 |
119 | player.complete(level: 7)
120 |
121 | if player.tracker.advance(to: 7){
122 | print("Podemos avanzar hasta el nivel 7")
123 | } else {
124 | print("El nivel 7 sigue bloqueado por ahora")
125 | }
126 |
--------------------------------------------------------------------------------
/15_methods.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/15_methods.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
14 |
15 |
19 |
20 |
24 |
25 |
29 |
30 |
34 |
35 |
39 |
40 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/16_subscripts.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | struct TimesTable{
4 | let multiplier:Int
5 |
6 | subscript(index: Int) -> Int {
7 | return multiplier * index
8 | }
9 | }
10 |
11 | let threeTimesTables = TimesTable(multiplier: 3)
12 | print("6x3 = \(threeTimesTables[6])")
13 |
14 | for idx in 0...100{
15 | print("\(idx) x 3 = \(threeTimesTables[idx])")
16 | }
17 |
18 |
19 | enum Planet : Int {
20 | case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
21 | static subscript(n: Int) -> Planet{
22 | return Planet(rawValue: n)!
23 | }
24 | }
25 |
26 | let mars = Planet[4]
27 | mars
28 |
29 |
30 |
31 | struct Matrix {
32 |
33 | let rows : Int, columns : Int
34 | var grid : [Double]
35 |
36 | init(rows: Int, columns: Int) {
37 | self.rows = rows
38 | self.columns = columns
39 | grid = Array(repeating: 0.0, count: rows * columns)
40 | }
41 |
42 | func indexIsValid(row:Int, column:Int) -> Bool{
43 | return row>=0 && column >= 0 && row < rows && column < columns
44 | }
45 |
46 | subscript(row: Int, column: Int) -> Double {
47 | get{
48 | assert(indexIsValid(row: row, column: column), "Index out of range")
49 | return grid[(row*columns)+column]
50 | }
51 | set{
52 | assert(indexIsValid(row: row, column: column), "Index out of range")
53 | grid[(row*columns)+column] = newValue
54 | }
55 | }
56 |
57 | }
58 |
59 |
60 | var matrix = Matrix(rows: 15, columns: 15)
61 | matrix[0, 1] = 1.5
62 | matrix[1, 0] = 2.5
63 | matrix
64 |
65 | for row in 0..
2 |
3 |
4 |
--------------------------------------------------------------------------------
/16_subscripts.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/17_inheritance.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | class Vehicle {
4 |
5 | var currentSpeed = 0.0
6 | var description: String{
7 | return "Viajando a \(currentSpeed) km/h"
8 | }
9 | func makeNoise(){
10 | //do nothing, porque cada vehículo tiene su propia forma de hacer ruido
11 | print("El ruido depende del vehículo")
12 | }
13 | }
14 |
15 | let someVehicle = Vehicle()
16 | print(someVehicle.description)
17 |
18 |
19 | class Bicycle : Vehicle {
20 | var hasBasket = false
21 | }
22 |
23 | let bicycle = Bicycle()
24 | bicycle.hasBasket = true
25 | bicycle.currentSpeed = 15.0
26 |
27 | print(bicycle.description)
28 |
29 | class Tandem : Bicycle{
30 | var currentNumberOfPassengers = 0
31 | }
32 |
33 | let tandem = Tandem()
34 | tandem.hasBasket = true
35 | tandem.currentNumberOfPassengers = 2
36 | tandem.currentSpeed = 22.0
37 | print(tandem.description)
38 |
39 | class Train: Vehicle{
40 | final var numberOfWagons = 0
41 |
42 | override func makeNoise() {
43 | print("Chooo Chooo")
44 | }
45 | }
46 |
47 | let train = Train()
48 | train.makeNoise()
49 |
50 | tandem.makeNoise()
51 |
52 |
53 | class Car: Vehicle{
54 | var gear = 1
55 | override var description: String{
56 | return super.description + " en la marcha \(gear)"
57 | }
58 | }
59 |
60 | let car = Car()
61 | car.currentSpeed = 55
62 | car.gear = 3
63 | print(car.description)
64 | print(tandem.description)
65 |
66 |
67 |
68 | class AutomaticCar : Car{
69 | override var currentSpeed: Double{
70 | didSet{
71 | gear = Int(currentSpeed / 15.0) + 1
72 | }
73 | }
74 | }
75 |
76 | let automatic = AutomaticCar()
77 | automatic.currentSpeed = 65
78 | print(automatic.description)
79 |
80 | class Railway : Train{
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/17_inheritance.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/18_inits.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 |
4 | struct Fahrenheit {
5 | var temperature : Double
6 |
7 | init(){
8 | self.temperature = 32
9 | }
10 | }
11 |
12 | var f1 = Fahrenheit()
13 |
14 | struct Celsius {
15 | var temperature: Double
16 |
17 | init(fromFahrenheit fahrenheit: Double) {
18 | self.temperature = (fahrenheit - 32) / 1.8
19 | }
20 |
21 | init(fromKelvin kelvin:Double) {
22 | self.temperature = kelvin - 273.15
23 | }
24 |
25 | init(_ celsius: Double) {
26 | self.temperature = celsius
27 | }
28 | }
29 |
30 |
31 | let boilingPointOfWater = Celsius(fromFahrenheit: 212)
32 | let freezingPointOfWater = Celsius(fromKelvin: 273.15)
33 |
34 | struct Color{
35 | let red, green, blue: Double
36 | init(red: Double, green: Double, blue: Double) {
37 | self.red = red
38 | self.green = green
39 | self.blue = blue
40 | }
41 | init(white: Double) {
42 | self.red = white
43 | self.green = white
44 | self.blue = white
45 | }
46 | }
47 |
48 |
49 | let magenta = Color(red: 1, green: 0, blue: 1)
50 | let halfGrey = Color(white: 0.5)
51 | let green = Color(red: 0,green: 1,blue: 0)
52 |
53 | let bodyTemperature = Celsius(37)
54 |
55 | class SurveyQuestion {
56 | let text: String
57 | var response: String?
58 |
59 | init(text: String) {
60 | self.text = text
61 | }
62 |
63 | func ask() {
64 | print(text)
65 | }
66 | }
67 |
68 | let q1 = SurveyQuestion(text: "¿Te gustan los tacos?")
69 | q1.ask()
70 | q1.response = "Si, me encatan todos ellos"
71 |
72 | //Designado -> Designado super clase
73 | //Conveniencia -> Otro init de la misma clase
74 | //El último init que se llame siempre debe ser designado
75 |
76 | class Vehicle {
77 | var numberOfWheels = 0
78 | var description: String{
79 | return "\(numberOfWheels) ruedas"
80 | }
81 | }
82 |
83 | let vehicle = Vehicle()
84 | vehicle.description
85 |
86 | class Bicycle: Vehicle{
87 | override init() {
88 | super.init()
89 | numberOfWheels = 2
90 | }
91 | }
92 |
93 | let bicycle = Bicycle()
94 | bicycle.description
95 |
96 |
97 | class Hoverboard: Vehicle{
98 | var color: String
99 | init(color: String){
100 | self.color = color
101 | //aquí se llama implícitamente a super.init()
102 | }
103 | override var description: String{
104 | return "\(super.description) en el color \(self.color)"
105 | }
106 | }
107 |
108 | let hoverboard = Hoverboard(color: "Silver")
109 | hoverboard.description
110 |
111 | enum TemperatureUnit{
112 | case kelvin, celsius, fahrenheit
113 |
114 | init?(symbol: Character){
115 | switch symbol {
116 | case "K":
117 | self = .kelvin
118 | case "C":
119 | self = .celsius
120 | case "F":
121 | self = .fahrenheit
122 | default:
123 | return nil
124 | }
125 | }
126 | }
127 |
128 | let someUnit = TemperatureUnit(symbol: "X")
129 |
130 |
131 | class Product{
132 | let name: String
133 | init?(name: String) {
134 | if name.isEmpty{
135 | return nil
136 | }
137 | self.name = name
138 | }
139 | }
140 |
141 | class CartItem: Product{
142 | let quantity: Int
143 | init?(name: String, quantity: Int){
144 | if quantity < 1{
145 | return nil
146 | }
147 | self.quantity = quantity
148 | super.init(name: name)
149 | }
150 | }
151 |
152 | if let someSocks = CartItem(name: "Socks", quantity: 2){
153 | print("\(someSocks.name) - \(someSocks.quantity)")
154 | }
155 |
156 |
157 |
158 |
159 | class Bank {
160 | static var coinsInBank = 2_000
161 | static func distribute(coins numberOfCoinsRequested:Int) -> Int {
162 | let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
163 | coinsInBank -= numberOfCoinsToVend
164 | return numberOfCoinsToVend
165 | }
166 | static func receive(coins: Int){
167 | coinsInBank += coins
168 | }
169 | }
170 |
171 | class Player {
172 | var coinsInPurse: Int
173 | init(coins: Int){
174 | self.coinsInPurse = Bank.distribute(coins: coins)
175 | }
176 | func win(coins: Int) {
177 | coinsInPurse += Bank.distribute(coins: coins)
178 | }
179 |
180 | deinit {
181 | Bank.receive(coins: coinsInPurse)
182 | }
183 |
184 | }
185 |
186 |
187 |
188 | var playerOne: Player? = Player(coins: 100)
189 | Bank.coinsInBank
190 | playerOne!.win(coins: 2_000)
191 | Bank.coinsInBank
192 |
193 | playerOne = nil
194 | Bank.coinsInBank
195 |
--------------------------------------------------------------------------------
/18_inits.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/18_inits.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
14 |
15 |
19 |
20 |
24 |
25 |
29 |
30 |
34 |
35 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/19_optional_chaining.playground/Contents.swift:
--------------------------------------------------------------------------------
1 | import UIKit
2 |
3 | class Person {
4 | var residence: Residence?
5 | }
6 |
7 | class Residence{
8 | var rooms = [Room]()
9 | var numberOfRooms : Int {
10 | return rooms.count
11 | }
12 | subscript(i: Int) -> Room{
13 | get {
14 | return rooms[i]
15 | }
16 | set {
17 | rooms[i] = newValue
18 | }
19 | }
20 | var address: Address?
21 |
22 |
23 | func printNumberOfRooms(){
24 | print("El número de habitaciones es \(numberOfRooms)")
25 | }
26 | }
27 |
28 | class Room{
29 | let name: String
30 | init(name: String){
31 | self.name = name
32 | }
33 | }
34 |
35 | class Address {
36 | var buildingName: String?
37 | var buildingNumber: String?
38 | var street: String?
39 |
40 | func buildingIdentifier() -> String?{
41 | if let buildingNumber = buildingNumber, let street = street{
42 | return "\(buildingNumber), \(street)"
43 | }else if buildingName != nil{
44 | return buildingName
45 | } else{
46 | return nil
47 | }
48 | }
49 | }
50 |
51 |
52 |
53 | let edgar = Person()
54 |
55 | if let roomCount = edgar.residence?.numberOfRooms{
56 | print("La casa de Edgar tiene \(roomCount) habitación(es)")
57 | }else{
58 | print("Edgar no tiene casa")
59 | }
60 |
61 |
62 | func createAddress() -> Address{
63 | print("La función ha sido llamada")
64 |
65 | let someAddress = Address()
66 | someAddress.buildingNumber = "13"
67 | someAddress.street = "Calle de Platzi"
68 |
69 | return someAddress
70 | }
71 |
72 | edgar.residence?.address = createAddress()
73 | edgar
74 | edgar.residence?.printNumberOfRooms()
75 |
76 | if edgar.residence?.printNumberOfRooms() != nil{
77 | print("He podido obtener el número de habitaciones")
78 | } else{
79 | print("NO ha sido posible saber el número de habitaciones")
80 | }
81 |
82 |
83 | if (edgar.residence?.address = createAddress()) != nil {
84 | print("Ha sido posible configurar la dirección de Edgar")
85 | } else {
86 | print("Seguimos sin saber donde vive Edgar")
87 | }
88 |
89 |
90 | if let firstRoomName = edgar.residence?[0].name {
91 | print("La primera habitación es de \(firstRoomName)")
92 | }else{
93 | print("La primera habitación no sabemos de quien es")
94 | }
95 |
96 | edgar.residence?[0] = Room(name: "Bathroom")
97 |
98 | let edgarHouse = Residence()
99 | edgarHouse.rooms.append(Room(name:"Bathroom"))
100 | edgarHouse.rooms.append(Room(name:"Living Room"))
101 | edgarHouse.rooms.append(Room(name:"Kitchen"))
102 | edgar.residence = edgarHouse
103 |
104 | if let firstRoomName = edgar.residence?[0].name {
105 | print("La primera habitación es de \(firstRoomName)")
106 | }else{
107 | print("La primera habitación no sabemos de quien es")
108 | }
109 |
110 | edgar.residence?.address = createAddress()
111 |
112 | if let edgarStreet = edgar.residence?.address?.street{
113 | print("La casa de Edgar está en la calle \(edgarStreet)")
114 | }else{
115 | print("No se donde vive Edgar")
116 | }
117 | edgar
118 |
119 |
120 | if let buildingIdentifier = edgar.residence?.address?.buildingIdentifier(){
121 | print("Edgar vive en \(buildingIdentifier)")
122 | }
123 |
124 | if let _ = edgar.residence?.address?.buildingIdentifier()?.hasPrefix("13"){
125 | print("Edgar vive en el número 13")
126 | } else{
127 | print("Edgar no vive en el número 13")
128 | }
129 |
--------------------------------------------------------------------------------
/19_optional_chaining.playground/contents.xcplayground:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/19_optional_chaining.playground/timeline.xctimeline:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
9 |
10 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # curso-swift5
2 |
--------------------------------------------------------------------------------