## Functions
If you provide an external parameter name for a parameter, that external name must always be used when calling the function.
~~~
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"
~~~
~~~
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
for character in string {
if character == characterToFind {
return true
}
}
return false
}
let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
// containsAVee equals true, because "aardvark" contains a "v"
~~~
~~~
func join(string s1: String, toString s2: String,
withJoiner joiner: String = " ") -> String {
return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: "-")
// returns "hello-world”
join(string: "hello", toString: "world")
// returns "hello world"
~~~
~~~
func join(s1: String, s2: String, joiner: String = " ") -> String {
return s1 + joiner + s2
}
join("hello", "world", joiner: "-")
// returns "hello-world” 有默認值的參數,如果你沒有使用外部參數名,Swift會自動提供一個和內部參數名一樣的外部參數名
~~~
~~~
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers
~~~
A function may have at most one variadic parameter, and it must always appear last in the parameter list, to avoid ambiguity when calling the function with multiple parameters.
If your function has one or more parameters with a default value, and also has a variadic parameter, place the variadic parameter after all the defaulted parameters at the very end of the list.
形參默認是常量,如果要改變形參,需要用var顯式聲明為變量 // swift中有許多默認情況和主流(比如C\C++)語言都是相反的,它將更常見的情況設定為默認
~~~
func alignRight(var string: String, count: Int, pad: Character) -> String {
let amountToPad = count - countElements(string)
for _ in 1...amountToPad {
string = pad + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello"
~~~
In-out parameters cannot have default values, and variadic parameters cannot be marked as inout. If you mark a parameter as inout, it cannot also be marked as var or let.
~~~
func swapTwoInts(inout a: Int, inout b: Int) { // 類似于引用傳參
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"
~~~
像定義常量或變量一樣定義函數:
~~~
var mathFunction: (Int, Int) -> Int = addTwoInts
println("Result: \(mathFunction(2, 3))")
// prints "Result: 5”
let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int) -> Int
~~~
~~~
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"
~~~
Swift支持嵌套函數:
~~~
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
~~~
- About Swift
- The Basics
- Basic Operators
- String and Characters
- Collection Types
- Control Flow
- Functions
- Closures
- Enumerations
- Classes and Structures
- Properties
- Methods
- Subscripts
- Inheritance
- Initialization
- Deinitialization
- Automatic Reference Counting
- Optional Chaining
- Type Casting
- Nested Types
- Extensions
- Protocols
- Generics
- Advanced Operators
- A Swift Tour