课程来自慕课网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<T>(_ num1: inout T, _ num2: inout T) {
(num1,num2) = (num2,num1)
}
var a = 1.0
var b = 2.0
swapTowNum(&a, &b)
- 泛型类型
struct Stack<T> {
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<Int>()
s.push(1)
s.pop()
网友评论