extensionArray{ funcfilter(includeElement: Element -> Bool) -> [Element] { var result: [Element] = [] for x inselfwhere includeElement(x) { result.append(x) } return result } }
Reduce
1 2 3 4 5 6 7 8
extensionArray{ funcreduce<T>(initial: T, combine: (T, Element) -> T) -> T { var result = initial for x inself { result = combine(result, x) } return result } }
用reduce实现map跟filter的版本
1 2 3 4 5 6 7 8 9 10 11 12 13
extensionArray{ funcmapUsingReduce<T>(transform: Element -> T) -> [T] { returnreduce([]) { result, x in return result + [transform(x)] } }
funcfilterUsingReduce(includeElement: Element -> Bool) -> [Element] { returnreduce([]) { result, x in return includeElement(x) ? result + [x] : result } } }
func ??<T>(optional: T?, defaultValue: T) -> T { iflet x = optional { return x } else { return defaultValue } }
//为了避免defaultValue的无效求值 in x operator ?? { associativityrightprecedence110 }
func ??<T>(optional: T?, @autoclosure defaultValue: () -> T) -> T { iflet x = optional { return x } else { return defaultValue() } }
分支上的可选值
1 2 3 4 5 6 7 8 9 10 11 12 13
//switch中的使用 switch madridPopulation { case0?: print("Nobody in Madrid") case (1..<1000)?: print("Less than a million in Madrid") case .Some(let x): print("\(x) people in Madrid") case .None: print("We don't know about Madrid") }
//guard中的使用 funcpopulationDescriptionForCity(city: String) -> String? { guardlet population = cities[city] else { returnnil } return"The population of Madrid is \(population * 1000)" }