- 忽略参数标签 _ xx: xxx
func greet(_ name:String) ->String{
return "hello,\(name)"
}
let kname = greet("jack")
- 设置默认参数值
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 2 ){
如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
}
- 可变参数 一个函数最多只能拥有一个可变参数。
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
print(arithmeticMean(1,2,3))
- 输入输出参数 函数修改变量 - inout
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var height = 120
var width = 60
swapTwoInts(&height, &width)
// height = 60, width = 120
- 函数类型作为返回类型
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func stepForward(_ input: Int) -> Int {
return input + 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}
- 闭包表达式语法
let blockHs = {(s1:String, s2:String) ->Bool in
return s1.count > s2.count
}
- 尾随闭包
func someFunctionThatTakesAClosure(closure: () -> Void) {
// 函数体部分
}
/*以下是不使用尾随闭包进行函数调用*/
someFunctionThatTakesAClosure(closure: {
// 闭包主体部分
})
/*以下是使用尾随闭包进行函数调用*/
someFunctionThatTakesAClosure() {
// 闭包主体部分
}
- 逃逸闭包 - @escaping
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}
- 自动闭包 自动闭包让你能够延迟求值
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let customerProvider = { customersInLine.remove(at: 0) }
print(customersInLine.count) // 打印出 5
customerProvider() // 执行
print(customersInLine.count) // 打印出 4
- 将闭包作为参数传递给函数时
func serve(customer customerProvider: () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: {customersInLine.remove(at: 0) })
// 打印出 "Now serving Alex!"
- 将参数标记为 @autoclosure 来接收一个自动闭包
func serveE(customer customerProvider: @autoclosure () -> String) {
print("Now serving \(customerProvider())!")
}
serveE(customer: customersInLine.remove(at: 0))
- 泛型函数
func swapTwoValues<T>(_ a: inout T, _ b: inout T){
let temporaryA = a
a = b
b = temporaryA
}
- 枚举语法
enum CompassPoint {
case north
case south
case east
case west
}
var directionToHead = CompassPoint.west
swift学习电梯:
swift-基础类型
swift-函数
swift-类和结构体