Swift笔记 - 13.闭包、捕获、局部作用域、成员重写、Swift指针及访问冲突

Swift笔记 - 13.闭包、捕获、局部作用域、成员重写、Swift指针及访问冲突

闭包中的捕获列表

class Person {
    var fn: (() -> ())?
    func run() { print ("run") }
    deinit { print ("deinit") }
}
func test() {
    let p = Person()
    p.fn = { p.run0) }
}
test ()
p.fn = { [weak p] in
    p?.run()
}

p.fn = { [unowned p] in
    p. run()
}

p.fn = { [weak wp = p, unowned up = p, a = 10 + 20] in
    wp?.run()
}
class Person {
    lazy var fn: (() = { [weak self] in
        self?.run()
    }
    func run() { print ("run") }
    deinit { print ("deinit") }
}
class Person {
    var age: Int = 0
    lazy var getAge: Int = {
        self.age
    }()
    deinit { print ("deinit") }
}

非逃逸与逃逸闭包

import Dispatch
typealias Fn = 0) -> ()

//fn是非选逸闭包
func test1(_ fn: Fn) { fn() }

//fn是选逸闭包
var gFn: Fn?
func test2(_ fn: @escaping Fn) { gFn = fn }

//fn是选逸闭包
func test3(_ fn: @escaping Fn) {
    DispatchQueue.global().async {
        fn()
    }
}

class Person {
    var fn: Fn
    //fn是选逸朗包
    init(fn: @escaping Fn) {
        self.fn = fn
    }
    func run() {
        //Dispatchoueue.global().async也是一个逃逸闭包
        //它用到了实例成员(属性、方法),编译器会强制要求明确写出self
        DispatchQueue.global().async {
            self.fn()
        }
    }
}
typealias Fn = () -> ()
func other1(_ fn: Fn) { fn() }
func other2(_ fn: @escaping Fn) { fn() }
func test (value: inout Int) -> Fn {
    other1 { value -= 1 }
    //error:逃逸闭包不能捕获inout参数
    other2 { valve += 1 }
    
    func plus(){ value += 1 }
        //error:逃逸闭包不能捕获inout参数
        return plus
    }
}

局部作用域

do {
    let dog1 = Dog()
    dog1.age = 10
    dog1.run()
}
do {
    let dog2 = Dog()
    dog2.age = 10
    dog2.run()
}

成员的重写

public class Person {
    private var age: Int = 0
}
public class Student : Person {
    override var age: Int {
        set {}
        get {10}
    }
}

public class Person {
    private var age: Int = 0
    
    public class Student : Person {
        override var age: Int {
            set {}
            get {10}
        }
    }
}

存在内存访问冲突

//不存在内存访问冲突
func plus(_ num: inout Int) -> Int { num + 1 }
var number = 1
number = plus(&number)

//存在内存访问冲突
// Simultaneous accesses to 0x0, but modification requires exclusive access
var step = 1
func increment(_ num: thout Int) { num += step }
increment(&step)

//解决内存访问冲突
var copyOfStep = step
increment (&copyOfStep)
step = copyOfStep
func balance(_ x: inout Int, _ y: inout Int) {
    let sum = x + y
    y = sum / 2
    x = sum - x 
}
var num1 = 42
var num2 = 30
balance(&num1, &num2) // OK
balance(&num1, &num1) // Error

struct Player {
    var name: String
    var health: Int
    var energy: Int
    mutating func shareHealth(with teammate: inout Player) {
        balance (&teammate.health, Shealth)
    }
}
var oscar = Player(name: "Oscar", health: 10, energy: 10)
var maria = Player(name: "Maria", health: 5, energy: 10)
oscar.shareHealth(with: Smaria) // OK
oscar.shareHealth(with: Soscar) // Error

var tulpe = (health: 10, energy: 20)
// Error
balance(&tulpe. health, &tulpe.energy)
var holly = Player(name: "Holly", health: 10, energy: 10)
// Error
balance(&holly.health, &holly.energy)
// Ok
func test() {
    var tulpe = (health: 10, energy: 20)
    balance(&tulpe.health, &tulpe.energy)
    var holly = Player(name: "Holly", health: 10, energy: 10)
    balance(&holly.health, &holly.energy)
}
test()

Swift当中的指针

var age = 10
func test1(_ pt: UnsafeMutablePointer<Int>) {
    ptr.pointee += 10
}
func test2(_ ptr: UnsafePointer<Int>) {
    print (ptr.pointee)
}
test1(&age)
test2(&age) // 20
print(age) // 20

var age = 10
func test3(_ pt: UnsafeMutableRawPointer)
    ptr.storeBytes(of: 20, as: Int.self)
}
func test4(_ ptr: UnsafeRawPointer) {
    print (ptr. load (as: Int.self))
}
test3(&age)
test4(&age) // 20
print(age) // 20

var arr = NSArray(objects: 11, 22, 33, 44)
arr.enumerateObjects { (obj, idx, stop) in
    print(idx, obj)
    if idx == 2 { // 下标为2就停止遍历
        stop. pointee = true
    }
}

var arr = NSArray (objects: 11, 22, 33, 44)
for (idx, obj) in arr.enumerated() {
    print(idx, obi)
    if idx == 2 {
        break
    }
}

var arr = NSArray(objects: 11, 22, 33, 44)
for (idx, element) in arr.enumerated() {
    print(idx, element)
    if idx == 2 { break }
}

获得某个变量的指针

var age = 11
var ptr1 = withUnsafeMutablePointer(to: &age) { $0 }
var ptr2 = withUnsafePointer(to: &age) { $0 }
ptr1.pointee = 22
print (ptr2.pointee) // 22
print (age) // 22
var ptr3 = withUnsafeMutablePointer(to: &age) { UnsafeMutableRawPointer($0) }
var ptr4 = withUnsafePointer(to: &age) { UnsafeRawPointer($0) }
ptr3.storeBytes (of: 33, as: Int.self)
print(ptr4.load(as: Int.self)) // 33
print(age) // 33

获得指向堆空间实例的指针

class Person {}
var person = Person()
var ptr = withUnsafePointer(to: &person) { UnsafeRawPointer($0) }
var heapPtr = UnsafeRawPointer(bitPattern: ptr.load(as: UInt.self))
print(heapPtr!)

创建指针

var ptr = UnsafeRawPointer(bitPattern: 0x100001234)

// 创建
var ptr = malloc(16)
// 存
ptr?.storeBytes(of: 11, as: Int.self)
ptr?.storeBytes (of: 22, toByteOffset: 8, as: Int.self)
print((ptr?.load(as: Int.self))!) // 11
print((ptr?.load(fromByteOffset: 8, as: Int.self))!) // 22
//销毁
free (ptr)

var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.storeBytes(of: 11, as: Int.self)
ptr.advanced(by: 8).storeBytes (of: 22, as: Int.self)
print(ptr. load(as: Int.self)) // 11
print(ptr.advanced (by: 8).load(as: Int.self)) // 22
ptr.deallocate()

var ptr = UnsafeMutablePointer<Int>.allocate(capacity: 3)
ptr.initialize(to: 11)
ptr.successor().initialize(to: 22)
ptr.successor().successor().initialize(to: 33)

print(ptr.pointee) // 11
print ((ptr + 1).pointee) // 22
print ((ptr + 2).pointee) // 33

print (ptr [0]) // 11
print (ptr(1]) // 22
print (ptr[2]) // 33

ptr.deinitialize(count: 3)
ptr.deallocate()
class Person {
    var age: Int
    var name: String
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
    deinit ( print (name, "deinit")
}

var ptr = UnsafeMutablePointer<Person>.allocate(capacity: 3)
ptr.initialize(to: Person(age: 10, name: "Jack"'))
(ptr + 1).initialize(to: Person(age: 11, name: "Rose"))
(ptr + 2).initialize(to: Person(age: 12, name: "Kate"))
// Jack deinit
// Rose deinit
// Kate deinit
ptr.deinitialize(count: 3) //反初始化
Iptr.deallocate()

指针之间的转换

var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)

ptr.assumingMemoryBound(to: Int.self).pointee = 11
(ptr + 8).assumingMemoryBound(to: Double.self).pointee = 22.0

print(unsafeBitCast(ptr, to: UnsafePointer<Int>.self).pointee) // 11
print(unsafeBitCast(ptr + 8, to: UnsafePointer<Double>.self).pointee) // 22.0

ptr.deallocate()
class Person {}
var person = Person()
//personobjectAddress存储的就是堆仝甸地址
var personObjectAddress = unsafeBitCast(person, to: UInt.self)
print(UnsafeRawPointer(bitPattern: personObjectAddress)!)

class Person {}
var person = Person()
var ptr = unsafeBitCast(person, to: UnsafeRawPointer.self)
print(ptr)

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