英文:
Difference between AssociatedType vs Self.AssociatedType
问题
以下是您要翻译的内容:
让我们假设我有这个协议:
protocol SomeProtocol {
associatedType Item: SomeOtherProtocol
var itemValue: Item
}
那个协议和这个协议之间有什么区别:
protocol SomeProtocol {
associatedType Item: SomeOtherProtocol
var itemValue: Self.Item
}
英文:
Let's say I have this protocol:
protocol SomeProtocol {
associatedType Item: SomeOtherProtocol
var itemValue: Item
}
What's the difference between that protocol and this one:
protocol SomeProtocol {
associatedType Item: SomeOtherProtocol
var itemValue: Self.Item
}
答案1
得分: 2
只返回翻译好的部分:
这类似于self.someProperty
和someProperty
之间的区别。通常它们指的是同一个属性,除非在更内部的作用域中也声明了名为someProperty
的东西,就像这样:
struct Foo {
let someProperty: Int
init(someProperty: Int) {
self.someProperty = someProperty
// 在这里,self.someProperty和someProperty意味着不同的东西
}
}
对于类型来说,这种情况发生得要少得多。我能想到的情况只涉及到局部类型:
struct Bar {
typealias Foo = Int
func foo() {
struct Foo {}
// 在这里,Foo指的是局部结构体,但Self.Foo指的是类型别名
}
}
即使不必要,添加Self.
也可以澄清你指的是在当前类型内声明的类型,而不是全局声明的其他类型。
struct Bar { }
protocol Foo {
associatedtype Bar
// 虽然"Self."不是必需的,
// 现在非常清楚我指的是哪种类型
var property: Self.Bar { get }
}
话虽如此,最好还是通过更好地命名你的类型来避免这种情况的发生
英文:
It's similar to the difference between self.someProperty
and someProperty
. Usually they refer to the same property, except in cases when something called someProperty
is also declared in a more inner scope, like this:
struct Foo {
let someProperty: Int
init(someProperty: Int) {
self.someProperty = someProperty
// here, self.someProperty and someProperty mean different things
}
}
For types, this occurs much more rarely. Off the top of my head, I can only think of situations involving a local type:
struct Bar {
typealias Foo = Int
func foo() {
struct Foo {}
// here, Foo refers to the local struct, but Self.Foo refers to the typealias
}
}
Adding Self.
(even when it is not necessary) can also clarify that you mean the type that is declared inside the current type, and not some other type declared globally.
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 }
}
That said, it is probably best to avoid situations like that in the first place, by naming your types better
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论