不透明类型

  1. 它是swift5.1新特性
  2. 不透明类型可以将函数的返回类型进行隐藏。
  3. 不透明的返回类型将更加灵活。
  4. 不透明类型是反泛型。泛型是调用者知道具体哪个类型,但是不透明类型是模块的设计者才知道具体是哪个类型。
  5. 不透明的返回类型要有统一的类型。

// 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 )
}
  1. 总结
    1. 作为函数返回值,不透明类型和协议的区别
      1. 不透明类型要求数据要有统一性,协议没有这个要求。这显得不透明类型更具有局限性,协议更加灵活。
      2. 关联协议不能用作函数的返回值,但是不透明类型确可以。
      3. 不透明类型有时候能进行比较,更加强大。
    2. 和泛型区别
      1. 泛型往往用在一个存储类型代表可以存储多种数据类型,或是用在函数的参数,代表可以接收很多种数据类型。而不透明类型是用在函数的返回值。
      2. 泛型是调用者知道明确的数据类型,但是不透明类型是模块的设计者才知道确定的返回类型。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章