Dast1

背景

在使用数组(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 协议添加扩展方法这种方式,可以更便捷也更安全的使用数组了!?

分类:

iOS

技术点:

相关文章:

  • 2021-09-05
  • 2021-12-17
  • 2021-11-11
  • 2021-04-09
  • 2021-10-05
猜你喜欢
  • 2021-05-02
  • 2021-06-12
  • 2021-08-06
  • 2021-06-15
  • 2022-12-23
  • 2022-03-10
  • 2022-03-04
相关资源
相似解决方案