美文网首页
Swift5.1学习随笔之指针

Swift5.1学习随笔之指针

作者: SAW_ | 来源:发表于2020-05-15 15:28 被阅读0次

    Swift中也有专门的指针类型,这些都被定义为Unsafe(不安全的),常见的有以下4种类型

    1. UnsafePointer<Pointee>类似于const Pointee *
    2. UnsafeMutablePointer<Pointee>类似于Pointee *
    3. UnsafeRawPointer类似于const void *
    4. UnsafeMutableRawPointer类似于void *

    func test1(_ ptr: UnsafePointer<Int>) {
        print("test1", ptr.pointee)
    }
    func test2(_ ptr: UnsafeMutablePointer<Int>) {
        ptr.pointee = 20
        print("test2", ptr.pointee)
    }
    
    var age = 10
    test1(&age) // test1 10
    test2(&age) // test2 20
    
    func test3(_ ptr: UnsafeRawPointer) {
        print("test3", ptr.load(as: Int.self))
    }
    func test4(_ ptr: UnsafeMutableRawPointer) {
        ptr.storeBytes(of: 30, as: Int.self)
    }
    
    var num = 10
    test3(&num) //test3 10
    test4(&num)
    print(num) // 30
    

    指针的使用例子🌰

    定义一个OC的数组,利用提供的enumerateObjects进行遍历。block里面的三个参数,第一个代表元素、第二个是索引,第三个就是指针了,这第三个指针就是OC中的BOOL *stop,因此在swift中的写法就是:

    var arr = NSArray(objects: 11, 22, 33, 44)
    arr.enumerateObjects { (<#Any#>, <#Int#>, <#UnsafeMutablePointer<ObjCBool>#>) in
        
    }
    
    arr.enumerateObjects { (element, index, stop) in
        print(index,element)
        if index == 2 {
            stop.pointee = true //等同于OC中 *stop = YES
        }
    }
    

    获得某个变量的指针
    var age = 10
    
    var ptr = withUnsafePointer(to: &age) { $0 }
    print(ptr.pointee) // 10
    
    var ptr2 = withUnsafeMutablePointer(to: &age) { $0 }
    ptr2.pointee = 30
    print(age) // 30
    
    var ptr3 = withUnsafePointer(to: &age) { (p) -> UnsafePointer<Int> in
        return p
    }
    print(ptr3.pointee) // 30
    
    var ptr4 = withUnsafeMutablePointer(to: &age) { (p) -> UnsafeMutablePointer<Int> in
        return p
    }
    ptr4.pointee = 50
    print(age) // 50
    
    var ptr5 = withUnsafePointer(to: &age) { UnsafeRawPointer($0) }
    print(ptr5.load(as: Int.self)) // 50
    
    var ptr6 = withUnsafeMutablePointer(to: &age) { UnsafeMutableRawPointer($0) }
    ptr6.storeBytes(of: 100, as: Int.self)
    print(age) // 100
    

    获得指向堆空间实例的指针
    class Person {}
    
    var person = Person()
    
    var ptr = withUnsafePointer(to: &person) { UnsafeRawPointer($0) }
    var address = ptr.load(as: UInt.self) // person 地址值
    var ptr2 = UnsafeMutableRawPointer(bitPattern: address) // 指向堆空间的地址值
    print(ptr2!) // 0x0000000100669c10
    
    print(Mems.ptr(ofRef: person)) // 0x0000000100669c10
    

    相关文章

      网友评论

          本文标题:Swift5.1学习随笔之指针

          本文链接:https://www.haomeiwen.com/subject/qwgqohtx.html