数组越界判定,这样更优雅

背景

在使用数组(swift)的编码过程中,不让程序崩溃是基本的要求,特别是在团队合作中时。

如果直接下面代码,会出现什么结果:

 private func collectionSafeBoundsTest1() {
        let arr = [0, 1, 2, 3]
        print(arr[100])
    }

运行后会发现程序崩溃了:Fatal error: Index out of range

如果每次使用数组时都判断一次是否超出下标边界,那么编码看起来会比较繁琐。有什么好的办法可以处理这种情况并且简化编码吗?

答案是:YES!

优雅的解决方法

可以通过使用扩展的方式:给 Collection 协议添加扩展方法。新建 swift 文件 Collection+Ex.swift ,添加如下代码:

import Foundation

extension Collection {
    subscript(safe index:Index)->Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

验证越界使用

然后在使用数组时,通过下面方式使用:

  private func collectionSafeBoundsTest2() {
        let arr = [0, 1, 2, 3]
        guard let ele = arr[safe: 100] else {
            print("下标超出数组边界!")
            return
        }
        print(ele)
    }

运行后不会崩溃,程序输出下标超出数组边界

验证常规使用

再验证下正常使用情况:

	    let arr = [0, 1, 2, 3]
        guard let ele = arr[safe: 1] else {
            print("下标超出数组边界!")
            return
        }
        print(ele)
    }

运行后输出 1,符合预期,程序也不会再崩溃了!

结论

通过给 Collection 协议添加扩展方法这种方式,可以更便捷也更安全的使用数组了!😋

posted @ 2023-01-31 22:46  Dast1  阅读(116)  评论(0编辑  收藏  举报