gpt4 book ai didi

swift - 为什么在类中需要声明 self 的结构中不需要声明 self ?

转载 作者:行者123 更新时间:2023-12-03 09:23:49 27 4
gpt4 key购买 nike

为什么要声明self在类中需要的结构中不需要?我不知道是否还有其他例子说明了这种情况,但在转义闭包的情况下,确实如此。如果闭包是非可选的(因此是非转义的),则不需要声明 self在两者中的任何一个。

class SomeClass {
let someProperty = 1

func someMethod(completion: (() -> Void)?) {}

func anotherMethod() {
someMethod {
print(self.someProperty) // declaring self is required
}
}
}

struct SomeStruct {
let someProperty = 1

func someMethod(completion: (() -> Void)?) {}

func anotherMethod() {
someMethod {
print(someProperty) // declaring self is not required
}
}
}

最佳答案

包含self的目的在带有引用类型的转义闭包(无论是可选闭包还是明确标记为 @escaping 的闭包)中使用属性时,可以使捕获语义明确。如果我们删除 self,编译器会警告我们引用:

Reference to property 'someProperty' in closure requires explicit use of 'self' to make capture semantics explicit.


但是,结构没有模糊的捕获语义。您总是在转义闭包内处理副本。它只对引用类型不明确,您需要 self明确可能引入强引用循环的位置,您正在引用哪个实例等。

顺便说一下,对于类类型,引用 self与属性结合并不是使捕获语义明确的唯一方法。例如,您可以使用“捕获列表”明确您的意图,或者:
  • 仅捕获属性(property):
     class SomeClass {
    var someProperty = 1

    func someMethod(completion: @escaping () -> Void) { ... }

    func anotherMethod() {
    someMethod { [someProperty] in // this captures the property, but not `self`
    print(someProperty)
    }
    }
    }
  • 或捕获 self :
     class SomeClass {
    var someProperty = 1

    func someMethod(completion: @escaping () -> Void) { ... }

    func anotherMethod() {
    someMethod { [self] in // this explicitly captures `self`
    print(someProperty)
    }
    }
    }

  • 这两种方法还可以明确您正在捕获的内容。

    关于swift - 为什么在类中需要声明 self 的结构中不需要声明 self ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64233385/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com