E文:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html
associatedtype用于protocol中 associatedtype类型是在protocol中代指一个确定类型并要求该类型实现指定方法
比如 我们定义一个protocol
1 2 3 4 5 6 | protocol Container { associatedtype ItemType mutating func append ( _ item : ItemType ) var count : Int { get } subscript ( i : Int ) - > ItemType { get } } |
之后实现这个协议
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | struct IntStack : Container { // original IntStack implementation var items = [ Int ]() mutating func push ( _ item : Int ) { items . append ( item ) } mutating func pop () - > Int { return items . removeLast () } // conformance to the Container protocol typealias ItemType = Int mutating func append ( _ item : Int ) { self . push ( item ) } var count : Int { return items . count } subscript ( i : Int ) - > Int { return items [ i ] } } |
其中items实现了ItemType这个代指变量
由于swift的类型推断,你实际上并不需要声明一个具体ItemType
的Int
作为定义的一部分IntStack
。由于IntStack
符合所有的要求Container
协议,swift可以推断出适当的ItemType
使用,只需通过查看类型append(_:)
方法的item
参数和标的返回类型。事实上,如果你删除typealias ItemType = Int
上面从代码行,一切仍然有效,因为很明显应该使用什么类型ItemType
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?