Created
March 23, 2016 15:01
-
-
Save gerson/8cad3954de405972063b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
/* | |
Swift es "type-safe" y usa "type-inference", lo cual significa que te ayudara mientras estas codeando. | |
Ejemplo si estas esperando un String evita que le envies un Int, de la misma | |
manera funciona cuando esperas un "no Optional" string y envias un "Optional" string. | |
*/ | |
//Ex: | |
func nombre(value: String){ | |
print(value) | |
} | |
var val1: String? | |
val1 = "maria" | |
//nombre(val1) | |
/* | |
Constantes y variables ("type inference") | |
se puede o no definir el tipo | |
*/ | |
let test1: String | |
var test2: String | |
//o | |
let test3 = "String 1" | |
var test4 = "String 2" | |
//Ademas puedes definir multiples variables en la misma linea indicando el tipo. | |
var red, green, blue: Double | |
let one, two, three: Int | |
// Las constantes no pueden ser modificadas, arrojan un error en tiempo de compilacion | |
// si se tratan de modificar | |
let languageName = "Swift" | |
//languageName = "Swift++" | |
// - Typealias | |
// Es una alternativa para nombrar un tipo existente. Ej: | |
typealias AudioSample = UInt16 | |
var maxAmplitudeFound = AudioSample.min | |
// - Closure | |
// typealias ClosureType = (ParameterTypes) -> (ReturnType) | |
typealias AnonymousCheck = (Int) -> Bool | |
var var1: AnonymousCheck = { | |
$0 > 0 | |
} | |
var1(-2) | |
var1(2) | |
// - Tuples | |
typealias Response = (code: Int, message: String) | |
var result:Response | |
result = (500, "Internal Server Error") | |
func getNewMail2 () -> Response { | |
return (200, "OK") | |
} | |
getNewMail2().code | |
getNewMail2().message | |
// - Tuples | |
// Es un grupo de multiples valores en un unico valor compuesto. | |
let http404Error = (404, "Not Found") | |
// No es necesario que los dos valores sean del mismo tipo. | |
// Las tuplas pueden ser descompuestas: | |
let (statusCode, statusMessage) = http404Error | |
print("The status code is \(statusCode)") | |
// Prints "The status code is 404" | |
let someTuple = (200, 500, "test1", "test2", true) | |
let (valor1, valor2, _, _, _) = someTuple | |
print(valor1) | |
print(valor2) | |
let tuple = (404, "Not Found") | |
tuple.0 // 404 | |
tuple.1 // Not Found | |
// - Optionals | |
let possibleNumber = "123" | |
let convertedNumber = Int(possibleNumber) | |
// convertedNumber is inferred to be of type "Int?", or "optional Int" | |
var serverResponseCode: Int? = 404 | |
// serverResponseCode contains an actual Int value of 404 | |
serverResponseCode = nil | |
// serverResponseCode now contains no value | |
// - Force Unwrapping | |
// Si estas completamente seguro que un optional tiene un valor y puede ser usado, puedes hacer el unwrapp | |
var surveyAnswer: String? | |
surveyAnswer = "YES" | |
print(surveyAnswer!) | |
// - Optional Binding o if let :) | |
let stringNumber = "1234" | |
if let actualNumber = Int(stringNumber) where actualNumber > 10000{ | |
print("\"\(stringNumber)\" has an integer value of \(actualNumber)") | |
} else { | |
print("\"\(stringNumber)\" could not be converted to an integer") | |
} | |
// Prints ""1234" has an integer value of 1234" | |
// - Implicitly Unwrapped Optionals | |
let possibleString: String? = "An optional string." | |
let forcedString: String = possibleString! // requires an exclamation mark | |
let assumedString: String! = "An implicitly unwrapped optional string." | |
let implicitString: String = assumedString // no need for an exclamation mark | |
// - Error Handling | |
/* | |
func makeASandwich() throws { | |
// this function may or may not throw an error | |
} | |
do { | |
try makeASandwich() | |
eatASandwich() | |
} catch Error.OutOfCleanDishes { | |
washDishes() | |
} catch Error.MissingIngredients(let ingredients) { | |
buyGroceries(ingredients) | |
} | |
*/ | |
// - Ternary Conditional Operator | |
let contentHeight = 40 | |
let hasHeader = true | |
var rowHeight: Int | |
if hasHeader { | |
rowHeight = contentHeight + 50 | |
} else { | |
rowHeight = contentHeight + 20 | |
} | |
// rowHeight is equal to 90 | |
// El anterior if y else se resume en esto: | |
rowHeight = contentHeight + (hasHeader ? 50 : 20) | |
// rowHeight is equal to 90 | |
// - Closed Range Operator | |
for index in 1...5 { | |
print("\(index) times 5 is \(index * 5)") | |
} | |
// 1 times 5 is 5 | |
// 2 times 5 is 10 | |
// ... hasta el 5 | |
// - Half-Open Range Operator | |
let names = ["Anna", "Alex", "Brian", "Jack"] | |
let count = names.count | |
for i in 0..<count { | |
print("Person \(i + 1) is called \(names[i])") | |
} | |
// Person 1 is called Anna | |
// ... hasta el i menor al total de nombres (3) | |
// - String Mutability | |
var variableString = "Horse" | |
variableString += " and carriage" | |
// variableString is now "Horse and carriage" | |
// character from a string | |
for character in "Dog!🐶".characters { | |
print(character) | |
} | |
// D | |
// o | |
// g | |
// ! | |
// 🐶 | |
// - Concatenating | |
let string1 = "hello" | |
let string2 = " there" | |
var welcome = string1 + string2 | |
// - String Interpolation | |
let multiplier = 3 | |
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" | |
// message is "3 times 2.5 is 7.5" | |
// - String indices | |
let greeting = "Guten Tag!" | |
greeting[greeting.startIndex] | |
// G | |
greeting[greeting.endIndex.predecessor()] | |
// ! | |
greeting[greeting.startIndex.successor()] | |
// u | |
let index = greeting.startIndex.advancedBy(7) | |
greeting[index] | |
// a | |
// - Inserting and Removing | |
var welcome1 = "hello" | |
welcome1.insert("!", atIndex: welcome1.endIndex) | |
// welcome now equals "hello!" | |
welcome1.removeAtIndex(welcome1.endIndex.predecessor()) | |
welcome1 | |
// welcome now equals "hello there" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment