- 在 Swift 中聲明方法的關(guān)鍵字 是
func
- 格式 `func 函數(shù)名稱(參數(shù)...) -> 返回類型`
- 沒有返回值的話 `-> ` 它以及后面的類型是不需要的
- 函數(shù)的聲明
- 沒有參數(shù),沒有返回值
- 沒有參數(shù),沒有返回值
func sayHello()
{
print("hello word")
}
- 有參數(shù),沒有返回值
* ````objc
func sayHello(name: String)
{
print("hello, \(name)")
}
// 參數(shù)可以添加默認(rèn)值
func sayHello(name: String = "Swift")
{
print("hello \(name)") // 不傳遞參數(shù)使用默認(rèn)值
}
- 有參數(shù),有返回值
* ````objc
func sayHello(name: String) -> String
{
return "hello, (name)"
}
print(sayHello("Swift")) // 輸出 hello, Swift
- 可變參數(shù)
* ````objc
func test(number:Int...) // 類型后面加上... number的類型會(huì)成為一個(gè)Int類型的數(shù)組
{
for num: Int in number
{
print(num)
}
}
test(1,2,3,4,5) // 循環(huán)輸出 1 2 3 4 5
- 函數(shù)作為參數(shù)或者返回值
// 函數(shù)作為參數(shù)或者返回值
// swift 能使用中文當(dāng)做方法名或者變
func 加法(a: Int, b: Int) -> Int 量名
{
return a + b
}
func 減法(a: Int, b: Int) -> Int
{
return a - b
}
var 加 = 加法 // 加上() 是調(diào)用方法
// 方法作為參數(shù)
func test(a: Int, b: Int, function: (Int,Int) -> Int ) -> Int
{
return function(a,b)
}
print(test(10, b: 1, function: 加))
// 方法作為返回值
func test(a: Int, b: Int, isTrue: Bool) -> Int
{
return isTrue ? 減法(a, b: b) : 加法(a, b: b)
}
print(test(10, b: 20, isTrue: false))
在方法內(nèi)部改變外面參數(shù)的值使用到的關(guān)鍵字是
inout
var number = 1
func test(inout a:Int)
{
a = 100
}
test(&number) // 發(fā)現(xiàn)方法參數(shù)前面出現(xiàn)了 `&`,取地址符,有oc功底的人應(yīng)該明白 inout關(guān)鍵字的實(shí)現(xiàn)方式了吧...沒錯(cuò)就是地址傳遞!
print(number) // 輸出 100
為參數(shù)起 別名
func sayHello(姓名 name: String) //`姓名`就是`別名`
{
print("hello \(name)")
}
sayHello(姓名: "Swift") // 調(diào)用方法的時(shí)候`別名`不能省略