Swift笔记 - 16.函数式编程

Swift笔记 - 16.函数式编程

函数式编程

var arr = [1, 2, 3, 4]
// [2, 4, 6, 8]
var arr2 = arr.map { $0 * 2 }
// [2, 4]
var arr3 = arr.filter {$0 % 2 == 0 }
// 10
var arr4 = arr.reduce (0) { $0 + $1 }
// 10
var arr5 = arr. reduce (0, +)

func double(_ i: Int) -> Int { i * 2 }
var arr = [1, 2, 3, 4]
// [2, 4, 6, 8]
print(arr.map (double) )

var arr = [1, 2, 3]
// [1], (2, 2], [3, 3, 3]]
var arr2 = arr.map { Array.init(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3]
var arr3 = arr.flatMap { Array.init(repeating: $0, count: $0) }
var arr = ["123", "test", "jack", "-30"]
// [Optional(123), nil, nil, Optional(-30)]
var arr2 = arr.map{ Int($0) }
// [123, -30]
var arr3 = arr.compactMap { Int($0) }

// 使用reduce实现map,filter的功能
var arr = [1,2,3,4]
// [2, 4, 6, 8]
print(arr.map{ $0 * 2 }
print(arr.reduce([]){ $0 + [ $1 * 2] })
// [2, 4]
print(arr.filter { $0 % 2 == 0 })
print (arr.reduce([]) { $1 %2 == 0 ? $0 + [$1] : $0})
let arr = [1, 2, 3]
let result = arr.lazy.map
(i: Int) -> Int in
print ("mapping \(i)")
return i * 2
}
print ("begin------")
print ("mapped", result[0])
print ("mapped", result(1])
print ("mapped", result[2])
print ("end------")

//output:
begin------
mapping 1
mapped 2
mapping 2
mapped 4
mapping 3
mapped 6
end------
var num1: Int? = 10
// Optional(20)
var num2 = num1.map ( $0 * 2 )

var num3: Int? = nil
// nil
var num4 = num3.map { $0 * 2 }


var num1: Int? = 10
// Optional(Optional(20))
var num2 = num1.map(Optional.some($0 * 2) }
// Optional(20)
var num3 = num1.flatMap ( Optional.some($0 * 2) }


var num1: Int? = 10
var num2 = (num1 != nil) ? (num1! + 10) : nil
var num3 = num1.map { $0 + 10 }


var fmt = DateFormatter()
ft.dateFormat = "yyyy-MM-dd"
var str: String? = "2011-09-10"
// old
var datel = str != nil ? fmt.date(from: str!) : nil
// new
var date2 = str.flatMap(fmt.date)


var score: Int? = 98
// old
var str1 = score != nil ? "socre is \(score!)": "No score"
// new
var str2 = score.map( "score is \($0)" } ?? "No score"
struct Person {
    var name: String
    var age: Int
}
var items = [
    Person(name: "jack", age: 20),
    Person(name: "rose", age: 21),
    Person(name: "kate", age: 22)
]
// old
func getPerson1(_ name: String) -> Person? {
    let index = items.firstIndex { $0.name == name }
    return index != nil ? items[index!] : nil
}
// new
func getPerson2(_ name: String) -> Person? {
    return items.firstIndex { $0.name == name }.map { items [$0] }
}
struct Person {
    var name: String
    var age: Int
    init?(_ json: [String: Any]) {
        guard let name = json["name"] as? String,
              let age = json["age"] as? Int else {
            return nil
        }
        self.name = name
        self. age = age
    }
}
var json: Dictionary? = ("name" : "Jack", "age" : 10]
// old
var p1 = json != nil ? Person(json!) : nil
// new
var p2 = json.flatMap(Person.init)
func add(_ v: Int) -> (Int) -> Int { { $0 + v } }
func sub(_ v: Int) -> (Int) -> Int  { $0 - v } }
func multiple(_ v: Int) -> (Int) -> Int { { $0 * v } }
func divide(_ v: Int) -> (Int) -> Int { $0 / v } }
func mod(_ v: Int) -> (Int) -> Int { { $0 % v }

infix operator >>> : AdditionPrecedence
func >>><A, B, C>(_ f1: @escaping (A) -> B,
                  _ f2: @escaping (B) -> C) -> (A) -> C { { f2(f1($0)) } }
  func add(_ v: Int) -> (Int) -> Int { { $0 + v } }

版权所有,转载请注明出处 luowei.github.io.