官术网_书友最值得收藏!

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)
主站蜘蛛池模板: 梧州市| 平湖市| 鹤岗市| 临猗县| 吴江市| 桃源县| 新余市| 烟台市| 新丰县| 远安县| 宜阳县| 陵川县| 仪陇县| 平度市| 庄河市| 平罗县| 黎川县| 德清县| 广元市| 宁城县| 岗巴县| 建昌县| 铜梁县| 中超| 武陟县| 吴旗县| 朝阳区| 盈江县| 河北区| 潜江市| 苍南县| 黄冈市| 浮梁县| 馆陶县| 霍城县| 黑山县| 临猗县| 监利县| 上林县| 尤溪县| 望奎县|