您的位置:首页 > 移动开发 > Swift

swift 的高阶函数的使用代码

2016-04-29 15:21 477 查看
//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

/// 使用map函数,进行数组内部数据的转换,map中接受一个转换函数
var array =  [1,2,3,4,5]
var newArray = array.map({$0 * 2})
print(newArray)

/// 使用reduce 函数 求和
var sum = array.reduce(0, combine: +)
print(sum)

/// 使用 filter来验证tweet中是否包含选定的若干关键字中的一个
let words = ["Swift","iOS","cocoa","OSX","tvOS"]
let tweet = "This is an example tweet larking about Swift"
let valid = !words.filter({tweet.containsString($0)}).isEmpty
print(valid)

let valid1 = words.contains(tweet.containsString)
print(valid1)

let valid2 = tweet.characters.split(" ").lazy.map(String.init).contains(Set(words).contains)
print(valid2)

/// 使用split map 分隔内容
let text = "窗前明月光 疑是地上霜 举头望明月 低头思故乡"
let lines = text.characters.split(" ").map(String.init)
print(lines[0])
print(lines[1])
print(lines[2])
print(lines[3])

/// 使用forEach 高阶函数便利
let name = "urai"
(1...4).forEach({print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))})
(1...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))}

// MARK: - 查找数组中符合条件的数据
extension SequenceType {

typealias Element = Self.Generator.Element

func partitionBy(fu: (Element) -> Bool) -> ([Element],[Element]) {

var first = [Element]()
var second = [Element]()

for el in self {

if fu(el) {

first.append(el)
}
else {

second.append(el)
}
}
return (first,second)
}
}

let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60}
print(part)

// MARK: - 一种更简介的查找方式
extension SequenceType {

func anotherpartitionBy(fu: (Self.Generator.Element) -> Bool) -> ([Self.Generator.Element],[Self.Generator.Element]) {

return (self.filter(fu),self.filter({!fu($0)}))
}
}

let part1 = [82, 58, 76, 49, 88, 90].anotherpartitionBy{$0 < 60}
print(part1)

/// 使用的是分区元组,但效率不如上边的高
var part2 = [82, 58, 76, 49, 88, 90].reduce( ([],[]), combine: {
(a:([Int],[Int]),n:Int) -> ([Int],[Int]) in
(n<60) ? (a.0+
,a.1) : (a.0,a.1+
)
})
print(part2)


代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: