- 它是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")
// 3. 圖形拼接
struct JoinedShape<T: Shape, U: Shape>: Shape {
var topShape: T
var bottomShape: U
func draw() -> String {
return topShape.draw() + "\n" + bottomShape.draw()
}
}
print(JoinedShape(topShape: aTriangle, bottomShape: aFlippedShape).draw(), terminator: "\n\n")
/**** 不透明的返回類型 ****/
// 4. 正方形
struct Square: Shape {
var size: Int
func draw() -> String {
let line = String(repeating: "*", count: size)
let arrTemp = Array(repeating: line, count: size)
return arrTemp.joined(separator: "\n")
}
}
var aSquare = Square(size: 3)
print(aSquare.draw(), terminator: "\n\n")
// 5. 三個圖形拼接 (不透明返回類型)
func joinShape() -> some Shape {
var topShape = Triangle(size: 2)
var middleShape = Square(size: 2)
var bottomShape = FlippedShape(shape: topShape)
var joinedShape = JoinedShape(topShape: topShape,
bottomShape: JoinedShape(topShape: middleShape, bottomShape: bottomShape)
)
return joinedShape
}
print(joinShape())
func join<T: Shape, U: Shape>(aShape: T, bShape: U) -> some Shape {
return JoinedShape(topShape: aShape, bottomShape:bShape )
}
- 總結
- 作爲函數返回值,不透明類型和協議的區別
- 不透明類型要求數據要有統一性,協議沒有這個要求。這顯得不透明類型更具有侷限性,協議更加靈活。
- 關聯協議不能用作函數的返回值,但是不透明類型確可以。
- 不透明類型有時候能進行比較,更加強大。
- 和泛型區別
- 泛型往往用在一個存儲類型代表可以存儲多種數據類型,或是用在函數的參數,代表可以接收很多種數據類型。而不透明類型是用在函數的返回值。
- 泛型是調用者知道明確的數據類型,但是不透明類型是模塊的設計者才知道確定的返回類型。