Swift ☞ 元组

一、定义与使用
两种定义方式及其使用方式

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");
        }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值