• Swift-范型


    Type Constraint

    <T: Comparable>  array.sorted()

    <Element: Equatable> array.contains{$0 != first}

    structures

    struct Queue<Element: Equatable> {
    }
    
    extension Queue {
        func isHomo() -> Bool {
            guard let first = elements.first else {return true}
            return !elements.contains{$0 != first}
        }
    }

    functions

    e.g.1

    // Comparable: 
    func mid<T: Comparable>(array: [T]) -> T? {
        guard !array.isEmpty else {return nil}
        return array.sorted()[(array.count - 1) / 2]
    }
    
    mid(array: [3, 2, 1, 5 ,4])
    mid(array: ["Shell", "Han", "Vermouth"])

    e.g.2

    func pairs<Key, Value>(from dictionary:[Key: Value]) -> [(Key, Value)] {
        return Array(dictionary)
    }

    protocols

    // 定义可加的协议
    // 类型扩展,使用协议
    protocol Summable {static func +(lhs: Self, rhs: Self) -> Self}
    extension Int: Summable {}
    extension Double: Summable {}
    extension String: Summable {}
    
    func add<T: Summable> (x: T, y:T) -> T {
        return x + y
    }
    
    let intSum = add(x: 1, y: 2)
    let doubleSum = add(x: 1.2, y: 2.3)
    let stringSum = add(x: "Shell", y: " Han")

    enum

    enum Result<Value> {
        case success(Value), failure(Error)
    }
    
    enum MathError<Error> {
        case divisionByZero
    }
    
    func divide(x: Int, by y: Int) -> Result<Int> {
        guard y != 0 else {
            return .failure(MathError.divisionByZero)
        }
        return .success(x / y)   
    }
  • 相关阅读:
    Adobe PS
    深入学习二叉树(04)平衡二叉树
    深入学习二叉树(03)二叉查找树
    C 知识点
    实战【docker 镜像制作与使用】
    从0到1了解 CI/CD
    单例模式的几种实现方式,使用场景以及优缺点
    设计模式之策略模式浅谈以及简单例子
    WPF几种渐变色
    Linq学习以及简单用法
  • 原文地址:https://www.cnblogs.com/HackHer/p/8522220.html
Copyright © 2020-2023  润新知