Swift 2 学习笔记 17.扩展和泛型

课程来自慕课网liuyubobobo老师


扩展
  • 扩展基础
class Rectangle{
    var width: Double = 0.0
    var height: Double = 0.0
    
    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }
}

extension Rectangle{
    func size() -> Double{
        return self.width * self.height
    }
    // 扩展中只能添加计算属性
    // 扩展中只能添加方便构造函数
}

let rect = Rectangle(width: 3, height: 2)
rect.size()  // 6
  • 扩展标准库
extension Int {
    var square: Int {
        return self*self
    }
}

let num = 6
num.square  // 36
  • 泛型函数
func swapTowNum(_ num1: inout T, _ num2: inout T) {
    (num1,num2) = (num2,num1)
}

var a = 1.0
var b = 2.0
swapTowNum(&a, &b)
  • 泛型类型
struct Stack {
    var items = [T]()
    
    func isEmpty() -> Bool {
        return items.count == 0
    }
    
    mutating func push(_ item: T) {
        items.append(item)
    }

    mutating func pop() -> T? {
        guard !self.isEmpty() else {
            return nil
        }
        return items.removeLast()
    }
}

var s = Stack()
s.push(1)
s.pop()

你可能感兴趣的:(Swift 2 学习笔记 17.扩展和泛型)