gpt4 book ai didi

swift - 为什么 typealias 使我的表达明确?

转载 作者:行者123 更新时间:2023-11-28 08:17:30 24 4
gpt4 key购买 nike

在下面的代码中,当我直接引用 C.ID 而不是使用 ID 类型别名时,我得到一个错误,“type of expression is ambiguous without more语境”。如果它们都引用相同的类型,为什么会产生歧义?

使用 typealias 并不是一个非常不方便的解决方法,但我确实发现错误令人困惑。

protocol OID: Hashable
{
var sha: String { get }
}

extension OID { public var hashValue: Int { return sha.hashValue } }

protocol CommitType
{
associatedtype ID: OID
}

class CommitEntry<C: CommitType>
{
typealias ID = C.ID

var lines1 = [ID: (a: UInt, b: UInt)]() // No problem
var lines2 = [C.ID: (a: UInt, b: UInt)]() // Error: ambiguous
}

最佳答案

来自Swift Documentation :

An associated type gives a placeholder name to a type that is used as part of the protocol. The actual type to use for that associated type is not specified until the protocol is adopted.

如果不在您的类中指定类型别名,编译器就不知道ID 是什么。因此,您需要使用 typealias 告诉它您希望 ID 使用什么您还可以使用类型推断告诉编译器:

protocol SomeProtocol {
associatedtype ItemType
subscript(i: Int) -> ItemType { get }
}

class SomeClass: SomeProtocol {
subscript(i: Int) -> Int {
return items[i]
}
}

这是可行的,因为在这种情况下,编译器可以推断 ItemType 必须是 Int。有关更多信息,请参阅链接 Swift Documentation .

关于swift - 为什么 typealias 使我的表达明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212058/

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