Skip to content

Instantly share code, notes, and snippets.

View furixturi's full-sized avatar
😈

Xiaoli Shen furixturi

😈
View GitHub Profile
/*
Closure example
(5) anonymous one-line closure
*/
let numbers = [12, 3, 6, 19]
let oddEven = numbers.map({ number in number % 2 == 0 ? "even" : "odd" })
/*
The value of oddEven:
["even", "odd", "even", "odd"]
*/
/*
Closure example
(4)Anonymous closure in curly braces with "in"
*/
let nums = [20, 9, 17, 12]
let oddEven = nums.map({ (number: Int) -> String in
return number % 2 == 0 ? "even" : "odd"
})
/*
Closure examples
(3) Function as a parameter.
*/
func testAtLeastOneMatch (list: [Int], condition: (Int) -> Bool) {
for i in list {
if condition(i) {
return true
}
}
/*
Closure examples
(2) return a function
*/
func makeAddition(toAdd: Int) -> ((Int) -> Int) {
func add(base: Int) -> {
return base + toAdd
}
/*
Closure examples
(1) function in function.
Inner function has access to variables of the outer function
*/
func outer() -> Int {
var outerVar = 5
func inner() {
outerVar += 5
}
// A typical Swift function signature
func myFunc(labelOfParam1 param1: String, _ param2: Int, param3: Float) -> Bool {
print(param1)
return param2 * Int(param3) > 0
}
// To call myFunc
myFunc(labelOfParam1: "Yo yo yo", 3, param3: 0.5)
/*
returns false
Because casting the param3 Float 0.5 to Int give us 0
func optionalTest() {
let myName: String? = nil
guard let name = myName
else {
print("I don't have a name")
return //You need to return or throw an error, otherwise the compiler complains:
//"error: 'guard' body may not fall through, consider using a 'return' or 'throw' to exit the scope
}
print("My name is \(name)")
var myName: String?
if let name = myName {
print("My name is \(name)")
} else {
print("I don't have a name")
}
/*
I don't have a name
*/
var nickName: String? = nil
var fullName: String = "Charlie Brown"
print("Hi, \(nickName ?? fullName)!")
/*
Hi, Charlie Brown!
*/
var mightNotExist: String?
mightNotExist == nil // true
var notOptional: String
notOptional == nil // Error! connat access a non-optional before initialization