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)
代码
相关文章推荐
- Swift--UI--UIButton
- Swift--UI--UIView
- 10个惊艳的Swift单行代码
- Swift构造器需要遵循的规则
- swift 扫描二维码/条形码,开启闪光灯,识别相册二维码
- swift2.0 学习笔记seven
- swift瀑布流自定义布局实现
- 验证字符串中是否还有其他字符 swift
- 使用Swift 字典模型互转 就是这么简单
- 【Swift】iOS开发笔记(二)
- Swift语言精要 - 浅谈结构体(Struct)
- Swift语言精要 - 浅谈结构体(Struct)
- 10个惊艳的Swift单行代码
- Swift--枚举类型
- 【Swift学习】Swift编程之旅---属性(十四)
- 美丽说demo(纯swift代码)
- Swift中的便利构造函数
- Swift中View层级结构调整
- Swift初始化方法顺序
- Swift 使用CollectionView 实现图片轮播封装