swift 高级用法

为了更好的学习alamofier,看看那些点不进去的符号方法吧(不知道,学起来真的是难受)

defer 修饰符

  1. defer : 在当前作用域执行完后再执行defer中的代码
    get方法中执行顺序为:
    1.lock.lock()
    2.return requests[task.taskIdentifier]
    3.defer { lock.unlock() }
//摘自alamofier -> sessionDelegate.swift (第170-179行)
  open subscript(task: URLSessionTask) -> Request? {
        get {
            lock.lock() ; defer { lock.unlock() }
            return requests[task.taskIdentifier]
        }
        set {
            lock.lock() ; defer { lock.unlock() }
            requests[task.taskIdentifier] = newValue
        }
    }

奇怪的函数

<-

这个方法其实就是这个,自己观察吧。。。有兴趣自己写写。(装逼)
摘自ObjectMapper ->EnumOperators.swift

/// Object of Raw Representable type
public func <- (left: inout T, right: Map) {
    left <- (right, EnumTransform())
}
public func >>> (left: T, right: Map) {
    left >>> (right, EnumTransform())
}


/// Optional Object of Raw Representable type
public func <- (left: inout T?, right: Map) {
    left <- (right, EnumTransform())
}

public func >>> (left: T?, right: Map) {
    left >>> (right, EnumTransform())
}


/// Implicitly Unwrapped Optional Object of Raw Representable type
public func <- (left: inout T!, right: Map) {
    left <- (right, EnumTransform())
}

// MARK:- Arrays of Raw Representable type

/// Array of Raw Representable object
public func <- (left: inout [T], right: Map) {
    left <- (right, EnumTransform())
}

public func >>> (left: [T], right: Map) {
    left >>> (right, EnumTransform())
}


/// Array of Raw Representable object
public func <- (left: inout [T]?, right: Map) {
    left <- (right, EnumTransform())
}

public func >>> (left: [T]?, right: Map) {
    left >>> (right, EnumTransform())
}


/// Array of Raw Representable object
public func <- (left: inout [T]!, right: Map) {
    left <- (right, EnumTransform())
}

// MARK:- Dictionaries of Raw Representable type

/// Dictionary of Raw Representable object
public func <- (left: inout [String: T], right: Map) {
    left <- (right, EnumTransform())
}

public func >>> (left: [String: T], right: Map) {
    left >>> (right, EnumTransform())
}


/// Dictionary of Raw Representable object
public func <- (left: inout [String: T]?, right: Map) {
    left <- (right, EnumTransform())
}

public func >>> (left: [String: T]?, right: Map) {
    left >>> (right, EnumTransform())
}


/// Dictionary of Raw Representable object
public func <- (left: inout [String: T]!, right: Map) {
    left <- (right, EnumTransform())
}

[]

这个其实就是用了subscript修饰符
摘自Map.swift

/// Sets the current mapper value and key.
    /// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
    public subscript(key: String) -> Map {
        // save key and value associated to it
        return self[key, delimiter: ".", ignoreNil: false]
    }
    
    public subscript(key: String, delimiter delimiter: String) -> Map {
        let nested = key.contains(delimiter)
        return self[key, nested: nested, delimiter: delimiter, ignoreNil: false]
    }
    
    public subscript(key: String, nested nested: Bool) -> Map {
        return self[key, nested: nested, delimiter: ".", ignoreNil: false]
    }
    
    public subscript(key: String, nested nested: Bool, delimiter delimiter: String) -> Map {
        return self[key, nested: nested, delimiter: delimiter, ignoreNil: false]
    }
    
    public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map {
        return self[key, delimiter: ".", ignoreNil: ignoreNil]
    }
    
    public subscript(key: String, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map {
        let nested = key.contains(delimiter)
        return self[key, nested: nested, delimiter: delimiter, ignoreNil: ignoreNil]
    }
    
    public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map {
        return self[key, nested: nested, delimiter: ".", ignoreNil: ignoreNil]
    }
    
    public subscript(key: String, nested nested: Bool, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map {
        // save key and value associated to it
        currentKey = key
        keyIsNested = nested
        nestedKeyDelimiter = delimiter
        
        if mappingType == .fromJSON {
            // check if a value exists for the current key
            // do this pre-check for performance reasons
            if nested == false {
                let object = JSON[key]
                let isNSNull = object is NSNull
                isKeyPresent = isNSNull ? true : object != nil
                currentValue = isNSNull ? nil : object
            } else {
                // break down the components of the key that are separated by .
                (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON)
            }
            
            // update isKeyPresent if ignoreNil is true
            if ignoreNil && currentValue == nil {
                isKeyPresent = false
            }
        }
        
        return self
    }

$0

如果你在闭包表达式中使用这些简写实际参数名,那么你可以在闭包的实际参数列表中忽略对其的定义,并且简写实际参数名的数字和类型将会从期望的函数类型中推断出来。 in 关键字也能被省略,因为闭包表达式完全由它的函数体组成:

不使用01这些来代替

let numbers = [1,2,5,4,3,6,8,7]
        sortNumbers = numbers.sorted(by: { (a, b) -> Bool in
            return a < b
        })
        print("numbers -" + "\(sortNumbers)")

使用0,1

let numbers = [1,2,5,4,3,6,8,7]
 var sortNumbers = numbers.sorted(by: {$0 < $1})
 print("numbers -" + "\(sortNumbers)")

高阶函数

map

可以对数组中的每一个元素做一次处理,并返回由新元素组成的集合。

// 计算字符串的长度
let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
func stringCount(string: String) -> Int {
    return string.characters.count
}
stringArray.map(stringCount)

stringArray.map({string -> Int in
    return string.characters.count
})

// $0代表数组中的每一个元素
stringArray.map{
    return $0.characters.count
}

flatMap

1. flatMap返回后的数组中不存在nil,同时它会把Optional解包

let array = ["Apple", "Orange", "Puple", ""]

let arr1 = array.map { a -> Int? in
    let length = a.characters.count
    guard length > 0 else { return nil }
    return length  
}
arr1 // [{some 5}, {some 6}, {some 5}, nil]

let arr2 = array.flatMap { a-> Int? in
    let length = a.characters.count
    guard length > 0 else { return nil}
    return length    
}    
arr2 // [5, 6, 5]

2. flatMap还能把数组中存有数组的数组(二维数组、N维数组)一同打开变成一个新的数组

let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

let arr1 = array.map{ $0 }
arr1 // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

let arr2 = array.flatMap{ $0 }
arr2 // [1, 2, 3, 4, 5, 6, 7, 8, 9]

3. flatMap也能把两个不同的数组合并成一个数组,这个合并的数组元素个数是前面两个数组元素个数的乘积

let fruits = ["Apple", "Orange", "Puple"]
let counts = [2, 3, 5]

let array = counts.flatMap { count in
    fruits.map ({ fruit in
         return fruit + "  \(count)"            
    })   
}
array // ["Apple 2", "Orange 2", "Puple 2", "Apple 3", "Orange 3", "Puple 3", "Apple 5", "Orange 5", "Puple 5"]

filer

过滤,可以对数组中的元素按照某种规则进行一次过滤

// 筛选出字符串的长度小于10的字符串
let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]
func stringCountLess10(string: String) -> Bool {
    return string.characters.count < 10
}
stringArray.filter(stringCountLess10)

stringArray.filter({string -> Bool in
    return string.characters.count < 10
})

// $0表示数组中的每一个元素
stringArray.filter{
    return $0.characters.count < 10
}

reduce

计算,可以对数组的元素进行计算

// 将数组中的每个字符串用‘、’拼接
let stringArray = ["Objective-C", "Swift", "HTML", "CSS", "JavaScript"]

func appendString(string1: String, string2: String) -> String {
    return string1 == "" ? string2 : string1 + "、" + string2
}
// reduce方法中的第一个参数是初始值
stringArray.reduce("", appendString)

stringArray.reduce("", {(string1, string2) -> String in
    return string1 == "" ? string2 : string1 + "、" + string2
})

// $0表示计算后的结果, $1表示数组中的每一个元素
stringArray.reduce("", {
    return $0 == "" ? $1 : $0 + "、" + $1

参考资料

感谢 感谢!
· 紫洁: swift中高阶函数map、flatMap、filter、reduce

· 逆流丶而上: Swift中0、1的实际含义

你可能感兴趣的:(swift 高级用法)