• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

swift3.0:associatedtype

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

E文:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html

associatedtype用于protocol中 associatedtype类型是在protocol中代指一个确定类型并要求该类型实现指定方法

比如 我们定义一个protocol

protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

  之后实现这个协议

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的类型推断,你实际上并不需要声明一个具体ItemTypeInt作为定义的一部分IntStack由于IntStack符合所有的要求Container协议,swift可以推断出适当的ItemType使用,只需通过查看类型append(_:)方法的item参数和标的返回类型。事实上,如果你删除typealias ItemType = Int上面从代码行,一切仍然有效,因为很明显应该使用什么类型ItemType


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
swift-画图-画矩形,虚线,圆和半圆发布时间:2022-07-13
下一篇:
Swift开发--Storyboard的使用教程发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap