1. hello world
var str = "Hello, playground" println("Hello, world (str)")
2.返回值为函数的函数
func addOne(number: Int) -> Int{ return 1 + number } func makeIncrementer() -> (Int -> Int){ return addOne } var increment = makeIncrementer() increment(7)
3.参数为函数的函数
func hasAnyMatches(list: [Int], lessThanTen: Int -> Bool) -> Bool{ for item in list{ if lessThanTen(item){ return true } } return false } func lessThanTen(number: Int) -> Bool{ return number < 10 } var numbers = [20, 19, 9, 12] hasAnyMatches(numbers, lessThanTen)
4.函数是一种特殊的闭包,除了使用大挂号,也可以使用in隔开闭包名和闭包的内容
numbers.map({ (number: Int)-> Int in let result = 3 * number return result })
闭包的简写
sort(&numbers) { $0 > $1 }
5.类
定义一个类
class Sharp: NSObject { var numberOfSides: Int = 0 var name: String init(name: String){//构造方法 self.name = name } func simpleDescription() -> String { return "A sharp with (numberOfSides) sides" } }
继承, init, override, get, set
class EquilateralTriangle: Sharp {//等边三角形 var sideLength : Double //init方法 init(name: String, sideLength: Double) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } //get方法和set方法 var perimeter: Double{//周长 get{ return 3 * sideLength } set{ sideLength = newValue / 3.0 } } func area() -> Double{ return sideLength * sideLength } //覆盖 override func simpleDescription() -> String { return "A EquilateralTriangle with sides of length (sideLength)." } }
6. 属性监视器
使用willSet, didSet实现
class traingleAndSquare: Sharp { var traingle: EquilateralTriangle{ willSet{ square.sideLength = newValue.sideLength } } var square: Square{ willSet{ traingle.sideLength = newValue.sideLength } } init(size: Double, name: String){ square = Square(name: name, length: size) traingle = EquilateralTriangle(name: name, sideLength: size) super.init(name: name) } }