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)   
}

 

posted @ 2018-03-07 14:34  ShellHan  阅读(211)  评论(0编辑  收藏  举报