- Learn Swift by Building Applications
- Emil Atanasov
- 437字
- 2025-04-04 16:55:54
What is a tuple?
A tuple is a bundle of different types (they may be the same) which have short names. In the preceding code, we have a tuple of two Int statements. The first one is named item, and the second one is named index. After the execution of the function, we will store the maximum item and its index in the tuple. If there are no items in the array, then the index will be -1.
It's possible to return an optional tuple type if there is a chance to return nil in some cases. The previous function may return nil if there are no items, and a valid result otherwise.
Each parameter may have a default value set. To set a default value, you have to declare it and add it right after the parameter's type. The following code is an example of this:
func generateGreeting(greet:String, thing:String = "world") -> String {
return greet + thing + "!"
}
print(generateGreeting(greet: "Hello "))
print(generateGreeting(greet: "Hello ", thing: " Swift 4"))
We can easily define a function which accepts zero or more variables of a specified type. This is called a variadic parameter. Each function definition could have, at most, one variadic parameter. It's denoted with ... after its type. In the body of the function, the type of this parameter is converted to an array. This array contains all passed values:
func maxValue(_ numbers:Int...) -> Int {
var max = Int.min
for v in numbers {
if max < v {
max = v
}
}
return max
}
print(maxValue(1, 2, 3, 4, 5))
//prints 5
One specific thing that we should know about function parameters is that they are constants. We can't mutate these by mistake. We should express this explicitly. To do so, we have to use the special word inout to mark the parameter. The inout parameters is added before the type of the parameter. We can pass variables to the inout parameters, but we can't pass constants. To pass a variable, we should mark this with & when calling the function. The inout parameters can't have default values. Also, variadic parameters can't be marked as such. In general, we can use the inout parameters to return values from a function, but this is not the same as returning values using return. This is an alternative way to let a function affect the outer world in the matrix. Check out the following code:
func updateVar(_ x: inout Int, newValue: Int = 5) {
x = newValue
}
var ten = 10
print(ten)
updateVar(&ten, newValue: 15)
print(ten)