传入函数的参数可以简单的用一个数组动态传入
func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf(42, 597, 12) sumOf(222,3333,44444,555555)
函数可以嵌套使用
func returnFifteen() -> Int { var y = 10 // 嵌套的函数 func add() { y += 5 } // 引用嵌套的函数 add() return y } returnFifteen()
一个函数可以返回另一个函数作为它的值
func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } //返回addOne(number:Int)->Int{....}给increment var increment = makeIncrementer() //传入参数 increment(7)
一个函数可以使用另一个函数作为它的传入参数
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, lessThanTen)
You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body.
var numbers = [20, 19, 7, 12] //----乘以3方法一 numbers.map({ (number: Int) -> Int in let result = 3 * number return result }) //----乘以3方法2 let mappedNumbers = numbers.map({ number in 3 * number }) mappedNumbers //----排序 let sortedNumbers = sorted(numbers) { $0 > $1 } sortedNumbers
对象和类
// class + 类名 新建一个类 //{ 属性和方法 定义} class Shape { var numberOfSides = 4 let color = "#3b5998" func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } func shadow(isShadowOn:Bool) ->String{ if(isShadowOn){ return "This is ON" }else{ return "This is OFF" } } } // 首先实例化一个类 // 用class.propert class.method 来引用属性和方法 var shape = Shape() // 改写属性 shape.numberOfSides = 7 // 调用方法 var shapeDescription = shape.simpleDescription() var shadow = shape.shadow(true)
//定义类Shape class Shape { //定义属性 let color = "#000" var numberOfSides = 0 var name: String //初始化 init(name: String) { self.name = name } //定义方法 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } //新建一个实例化Shape var shape = Shape(name: "Test_Shape") //设置属性 shape.numberOfSides = 7 //调用方法 var shapeDescription = shape.simpleDescription() //子类Square继承自Shape class Square: Shape { //添加属性 var sideLength: Double //自定义初始化方法 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } //添加的方法 func area() -> Double { return sideLength * sideLength } //复写父类方法 override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } //实例化一个Square let test = Square(sideLength: 5.2, name: "my test square") //调用方法 test.area() test.simpleDescription()
时间: 2024-10-26 07:37:51