swift AssociatedType与Self.AssociatedType的区别

bvjxkvbb  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(68)

假设我有这个协议:

protocol SomeProtocol {

associatedType Item: SomeOtherProtocol

var itemValue: Item

}

那个协议和这个协议有什么区别:

protocol SomeProtocol {

associatedType Item: SomeOtherProtocol

var itemValue: Self.Item

}
j9per5c4

j9per5c41#

它类似于self.somePropertysomeProperty之间的区别。通常它们引用相同的属性,除非在更内部的作用域中也声明了一个名为someProperty的东西,就像这样:

struct Foo {
    let someProperty: Int
    init(someProperty: Int) {
        self.someProperty = someProperty
        // here, self.someProperty and someProperty mean different things
    }
}

对于类型,这种情况很少发生。在我的脑海中,我只能想到涉及本地类型的情况:

struct Bar {
    typealias Foo = Int
    
    func foo() {
        struct Foo {}

        // here, Foo refers to the local struct, but Self.Foo refers to the typealias
    }
}

添加Self.(即使没有必要)也可以澄清您所指的是在当前类型内部声明的类型,而不是全局声明的其他类型。

struct Bar { }

protocol Foo {
    associatedtype Bar

    // though "Self." is not necessary,
    // it is now very clear which type I mean
    var property: Self.Bar { get }
}

也就是说,最好避免这种情况,首先要更好地命名你的类型:)

相关问题