//
// Associatedtype.swift
// SwiftCode
//
// Created by Alisa on 2022/4/17.
// Copyright © 2022 Alisa. All rights reserved.
//
import Foundation
/*
** 关联类型可以添加where约束子句
associatedtype是swift协议中一个很有用的关键字,其也是swift泛型编程思想的一种实现,在swift3中,associatedtype从语法上是不能追加where子句的,swift4
增强了associatedtype的功能,其可以使用where子句进行更加精准的约束
*/
//associatedtype与where联用约束子句
//容器协议
protocol Container{
//约束item泛型为Int类型
associatedtype Item where Item == Int
func append(_ item:Item)
var count:Int {get}
subscript(i:Int)-> Item{get}
}
class MyIntArray:Container{
//这个地方必须指定为Int,否则报错
typealias Item = Int
var innerArray = [Int]()
var count: Int{
get{
return self.innerArray.count
}
}
func append(_ item: Int) {
self.innerArray.append(item)
}
subscript(i: Int) -> Int {
return self.innerArray[i]
}
}
class AssociatedtypeWhere{
//associatedtype与where联用约束子句
func useAssociatedAndWhere(){
let myArray = MyIntArray()
myArray.append(2)
myArray.append(4)
myArray.append(6)
myArray.append(8)
print("my array count is:\(myArray.count)")
print("my array at i value is:\(myArray[2])")
/* 打印信息:
my array count is:4
my array at i value is:6
*/
}
}
12-01
7866
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-28
1346
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-15
1572
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)