Extending a Generic Type

When you extend a generic type, you do not provide a type parameter list as part of the extension's definition. Instead, the type parameter list from the original type definition is available within the body of the extension, and the original type parameter names are used to refer to the type parameters from the original definition.

The following example extends the generic Stack type to add a read-only computed property called topItem, which returns the top item on the stack without popping it from the stack:

extension Stack {
    var topItem: T? {
        return items.isEmpty ? nil : items[items.count - 1]
    }
}

The topItem property returns an optional value of type T. If the stack is empty, topItem returns nil; if the stack is not empty, topItem returns the final item in the items array.

Note that this extension does not define a type parameter list. Instead, the Stack type's existing type parameter name, T, is used within the extension to indicate the optional type of the topItem computed property.

The topItem computed property can now be used with any Stack instance to access and query its top item without removing it:

if let topItem = stackOfStrings.topItem {
    println("The top item on the stack is \(topItem).")
}
// prints "the top item on the stack is tres."
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 友人是我的高二高三同桌,相见如故。 一直想送她一份自己做的礼物,刚好发现了这玩意儿 买工具 磨菩提 打孔 安红豆跟...
    小非子阅读 377评论 0 0
  • 见过多少人 才会明白 让你哭的是你的喜欢 逗你笑的是喜欢你的 每个人都将会有一个最后陪伴 午间的风潇洒 午夜的风萧...
    绝对式人阅读 351评论 0 0
  • 啦啦啦,啦啦啦,今天是我22岁生日。这是我来到这个世界的第8026天。 因为要准备考研,整个暑假都贡献给了自习室...
    Augusttsy阅读 621评论 0 4
  • 一、蘑菇街 App 的组件化之路 二、iOS应用架构谈 组件化方案 三、蘑菇街 App 的组件化之路·续 四、iO...
    钱嘘嘘阅读 849评论 0 1