- 它是swift5.1新特性
- 不透明类型可以将函数的返回类型进行隐藏。
- 不透明的返回类型将更加灵活。
- 不透明类型是反泛型。泛型是调用者知道具体哪个类型,但是不透明类型是模块的设计者才知道具体是哪个类型。
- 不透明的返回类型要有统一的类型。
// 1. 三角形
protocol Shape {
func draw() -> String
}
struct Triangle: Shape {
var size: Int
func draw() -> String {
var arrStart = [String]()
for index in 1...size {
let start = String(repeating: "*", count: index)
arrStart.append(start)
}
return arrStart.joined(separator: "\n")
}
}
let aTriangle = Triangle(size: 3)
print(aTriangle.draw(),terminator:"\n\n")
// 2. 图形翻转
struct FlippedShape<T: Shape>: Shape {
var shape: T
func draw() -> String {
return shape.draw().split(separator: "\n").reversed().joined(separator: "\n")
}
}
let aFlippedShape = FlippedShape(shape: aTriangle)
print(aFlippedShape.draw(), terminator: "\n\n")
/