DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 9/100)

Swift

  • closure
  • trailing closure
  • shorthand param
import Cocoa // ## Function Closure // The parameters have moved inside the braces, and the in keyword is there to mark the end of the parameter list and the start of the closure’s body itself // example 1, closure that takes no parameter, return boolean let demo = { () -> Bool in print("Paying an anonymous person…") return true } // example 2, closure that takes 2 params, return string let payment = { (user: String, amount: Int) -> String in if user == "john" && amount == 10 { return "yes" } return "no" } print(payment("john", 8)) // Notice: We don't use parameter names when calling a closure. // payment(user: "john", amount: 8) --> incorrect // :warning: Closures cannot use external parameter labels. /* var cutGrass = { (length currentLength: Double) in // this is an invalid closure } */ // example 3, pass closure as function type parameter let team = ["Gloria", "Suzanne", "Piper", "Tiffany", "Tasha"] let captainFirstTeam = team.sorted(by: { (name1: String, name2: String) -> Bool in if name1 == "Suzanne" { return true } else if name2 == "Suzanne" { return false } return name1 < name2 }) print(captainFirstTeam) // ## Trailing closure // 1, swift can infer parameter and return types in closure when pass as func parameter // 2, remove `(by:`, start the closure directly let captainFirstTeam2 = team.sorted { name1, name2 in if name1 == "Suzanne" { return true } else if name2 == "Suzanne" { return false } return name1 < name2 } // ## shorthand syntax with $0, $1, etc. let captainFirstTeam3 = team.sorted { if $0 == "Suzanne" { return true } else if $1 == "Suzanne" { return false } return $0 < $1 } // ## Take function as parameter func makeArray(size: Int, using generator: () -> Int) -> [Int] { var numbers = [Int]() for _ in 0..<size { let newNumber = generator() numbers.append(newNumber) } return numbers } // ## Check point /* Your input is this: let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49] Your job is to: Filter out any numbers that are even Sort the array in ascending order Map them to strings in the format “7 is a lucky number” Print the resulting array, one item per line */ let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49] let result = luckyNumbers.filter({!$0.isMultiple(of: 2)}).sorted() .map({"\($0) is a luck number"}) for ele in result { print(ele) } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)