tellmeadr {(url: String) in print("hello!zhhooo!~\(url)") }
zhhooo.com从函数中一直传递到闭包运行。
其他例子:
1 2 3 4 5 6 7 8 9 10 11 12
funcmakePizza(addToppings: (Int) -> Void ) { print("The dough is ready.") print("The base is flat.") addToppings(3) } makePizza { (toppingCount: Int) in let toppings = ["ham", "salami", "onions", "peppers"] for i in0..<toppingCount { let topping = toppings[i] print("I'm adding \(topping)") } }
其他例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcgetDirections(to destination: String, then travel: ([String]) -> Void) { let directions = [ "Go straight ahead", "Turn left onto Station Road", "Turn right onto High Street", "You have arrived at \(destination)" ] travel(directions) } getDirections(to: "London") { (directions: [String]) in print("I'm getting my car.") for direction in directions { print(direction) } }
funczhhooo(url:(String) -> String){ print("Let's go!") let adr = url("zhhooo.com") print("Let's go to the \(adr)") }
zhhooo{(url:String) in return"https://\(url)/" }
其他例子:
1 2 3 4 5 6 7 8 9
funcencrypt(password: String, using algorithm: (String) -> String) { print("Encrypting password...") let result = algorithm(password) print("The result is \(result)") } encrypt(password: "t4ylor") { (password: String) in print("Using top secret encryption!") return"SECRET"+ password +"SECRET" }
简化代码及速记参数
在Swift中你可以简化你的代码,例如:
1 2 3 4 5
funczhhooo(url:(String) -> String){ print("Let's go!") let adr = url("zhhooo.com") print("Let's go to the \(adr)") }
let txt = zhhooo() txt("zhhooo.com") txt("zhhooo.com") txt("zhhooo.com")
其他例子:
1 2 3 4 5 6 7 8 9 10 11 12 13
funcstoreTwoValues(value1: String, value2: String) -> (String) -> String { var previous = value1 var current = value2 return { new in let removed = previous previous = current current = new return"Removed \(removed)" } } let store = storeTwoValues(value1: "Hello", value2: "World") let removed = store("Value Three") print(removed)