zoukankan      html  css  js  c++  java
  • 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)   
    }
  • 相关阅读:
    mysql 常用sql操作总结
    c# 安装windows服务
    c# Ajax后台动态分页
    c# SQLHelper总汇
    C#调用Web Service时的身份验证
    c#定时调用作业
    【转】Powerdesigner逆向工程从sql server数据库生成pdm
    aspx页面@Page指令解析
    C# 简单日志文本输出
    【摘抄】C# DateTime.Now详解
  • 原文地址:https://www.cnblogs.com/HackHer/p/8522220.html
Copyright © 2011-2022 走看看