Swift 基础

Swift Founction 和 Closures

2020-08-04  本文已影响0人  幸运者_Lucky

可变参数数量和参数泛型约束

  1. 可以使用 ..., 来设置可变参数数量
  2. 使用 where 约束泛型实现特定的协议
func sum<T>(_ numbers: T...) -> T where T: Numeric {
    var total: T = 0
    for number in numbers {
        total += number
    }
    return total
}
print(sum(1, 2, 3, 4, 5))
print(sum(1.1, 2, 3, 4, 5))

// print 
15
15.1

方法类型和嵌套方法

  1. swift 的 function 也是变量, 可以进行作为参数进行传递
  2. 可以在一个方法中嵌套其他的方法
    如下:
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")

// print
-4... 
-3... 
-2... 
-1... 
zero!

闭包和内部函数捕获对象

把方法赋值给比闭包的时候要注意循环引用的问题,

class A {
    var k: (() -> Void)?
    func a() {
        print("a run")
        func b() {
            print(self)
        }
        
        b()
    }
    
    deinit {
        print("a deinit")
    }
}

autoreleasepool {
    let a = A()
    a.a()
}

print("end")
class A {
    var k: (() -> Void)?
    func a() {
        print("a run")
        func b() {
            print(self)
        }
        
        k = b
    }
    
    deinit {
        print("a deinit")
    }
}

autoreleasepool {
    let a = A()
    a.a()
}

print("end")

// print 
a run
end
class A {
    var k: (() -> Void)?
    func a() {
        print("a run")
        weak var s = self
        func b() {
            if let s = s {
                print(s)
            }
        }

        k = b
    }
    
    deinit {
        print("a deinit")
    }
}

autoreleasepool {
    let a = A()
    a.a()
}

print("end")

// print
a run
a deinit
end

As an optimization, Swift may instead capture and store a copy of a value if that value is not mutated by a closure, and if the value is not mutated after the closure is created.

Swift also handles all memory management involved in disposing of variables when they are no longer needed.
上面的意思是, 闭包捕获值类型参数同样满足 copy on write.

类型方法

和类型属性一样, 可以使用 classstatic 进行修饰, 如果是 class 可以被子类继承, 值类型没有 class 进行修饰.

上一篇 下一篇

猜你喜欢

热点阅读