swift基础之透明类型

原创
2021/04/21 14:43
阅读数 59

透明类型 some 示例

protocol Shape {
    func draw() -> String
}

struct Triangle: Shape {
    var size: Int
    
    func draw() -> String {
        var result = [String]()
        for length in 1...size {
            result.append(String(repeating: "*", count: length))
        }
        return result.joined(separator: "\n")
    }
}

struct FlippedShape<T:Shape>: Shape {
    var shape: T
    
    func draw() -> String {
        let lines = shape.draw().split(separator: "\n")
        return lines.reversed().joined(separator: "\n")
    }
}

struct JoinedShape<T:Shape, U: Shape>: Shape {
    var top: T
    var bottom: U
    func draw() -> String {
        return top.draw() + "\n" + bottom.draw()
    }
}

struct Square: Shape {
    var size: Int
    func draw() -> String {
        let line = String(repeating: "*", count: size)
        let result = Array<String>(repeating: line, count: size)
        return result.joined(separator: "\n")
    }
}

let shape = Triangle(size: 6)

print(FlippedShape(shape: shape).draw())
/*
 
 ******
 *****
 ****
 ***
 **
 *
 
 */
print(JoinedShape(top: shape, bottom: shape).draw())
/*
 
 *
 **
 ***
 ****
 *****
 ******
 *
 **
 ***
 ****
 *****
 ******

 */
print(Square(size: 6).draw())
/*
 
 ******
 ******
 ******
 ******
 ******
 ******
 
 */


func makeTrapezoid() -> JoinedShape<Triangle, JoinedShape<Square, FlippedShape<Triangle>>> {
    let top = Triangle(size: 2)
    let middle = Square(size: 2)
    let bottom = FlippedShape(shape: top)
    let trapezoid = JoinedShape(top: top, bottom: JoinedShape(top: middle, bottom: bottom))
    return trapezoid
}

let trapezoid = makeTrapezoid()
print(trapezoid.draw())
/*
 
 *
 **
 **
 **
 **
 *
 
 */


//同样的功能用透明类型返回值更简洁
func makeTrapezoidTwo() -> some Shape {
    let top = Triangle(size: 2)
    let middle = Square(size: 2)
    let bottom = FlippedShape(shape: top)
    let trapezoid = JoinedShape(top: top, bottom: JoinedShape(top: middle, bottom: bottom))
    return trapezoid
}
let trapezoidTwo = makeTrapezoidTwo()
print(trapezoidTwo.draw())
/*
 
 *
 **
 **
 **
 **
 *
 
 */
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部