swift3.0:associatedtype

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

转载于:https://www.cnblogs.com/dctechnology/p/5989917.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值