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

标签 swift

在下面的代码中,当我直接引用 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/

相关文章:

swift - 我可以从 Storyboard 中实例化一个 Swift 自定义 UIView 而无需嵌套吗?

ios - 如何使用 Graphics Context 清除具有关闭路径的任何 imageView 的图像

objective-c - 在swift中实现objective-c协议(protocol)

ios - layoutifneeded 不会触发layoutSubviews

ios - SwiftUI 主列表可滚动标题 View 没有部分?

ios - 有没有办法在 Swift 中将特殊字符转换为普通字符?

swift - 在 NavigationBar 中嵌入 NavigationButton

c++ - 在桥接头文件中导入头文件导致的Swift编译错误

ios - 无法调用 'saveInBackgroundWithBlock'

swift - 在 Swift 中发布文件