//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" /// 使用map函数,进行数组内部数据的转换,map中接受一个转换函数
var array = [,,,,]
var newArray = array.map({$ * })
print(newArray) /// 使用reduce 函数 求和
var sum = array.reduce(, 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($)}).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[])
print(lines[])
print(lines[])
print(lines[]) /// 使用forEach 高阶函数便利
let name = "urai"
(...).forEach({print("Happy Birthday " + (($ == ) ? "dear \(name)":"to You"))})
(...).forEach{print("Happy Birthday " + (($ == ) ? "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 = [, , , , , ].partitionBy{$ < }
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($)}))
}
} let part1 = [, , , , , ].anotherpartitionBy{$ < }
print(part1) /// 使用的是分区元组,但效率不如上边的高
var part2 = [, , , , , ].reduce( ([],[]), combine: {
(a:([Int],[Int]),n:Int) -> ([Int],[Int]) in
(n<) ? (a.+[n],a.) : (a.,a.+[n])
})
print(part2)
代码