一、定义与使用
两种定义方式及其使用方式
let tuplesOne = ("max is 10","min is 5");
print(tuplesOne.0);
print(tuplesOne.1);
let tuplesTwo = (max: "max is 10",min: "min is 5");
print(tuplesTwo.max);
print(tuplesTwo.min);
分解方式:
let testTuples = ("monkey","pig");
let (猴子,╭︿︿︿╮ {/ o o /} ( (oo) ) ︶︶︶) = testTuples;
print(猴子)
print(╭︿︿︿╮ {/ o o /} ( (oo) ) ︶︶︶)
二、元组与函数
结合上面元组的定义,不难推断元组与函数的使用方式
func caculateMaxMin(scores: [Int]) -> (max: Int, min: Int) {
var max = scores[0];
var min = scores[0];
for score in scores[1..<scores.count] {
if score > max {
max = score;
}else if score < min {
min = score;
}
}
return (max ,min);
}
let receiveResult = caculateMaxMin([2,3,6]);
print("max is \(receiveResult.max)");//函数的返回值已经定义了max,如果没有定义,需要使用.0
print("min is \(receiveResult.min)");
既然swift语言是强类型语言,而且上面的代码在编译时并没有报错,也就是说很安全?
由于函数不会对传入的数组进行检查,所以,如果传入的数组为空,仍然会有运行时错误,此外,我们应当选用可选元祖返回类型,然后通过可选绑定避免运行时错误。
更改如下:
func caculateMaxMin(scores: [Int]) -> (max: Int, min: Int)? {
if scores.isEmpty {
return nil;
}
var max = scores[0];
var min = scores[0];
for score in scores[1..<scores.count] {
if score > max {
max = score;
}else if score < min
{
min = score;
}
}
return (max ,min);
}
if let receiveResult = caculateMaxMin([2,3,6]) {
print("max is \(receiveResult.max)");
print("min is \(receiveResult.min)");
}else {
print("return Nothing");
}