如何直观检查结构体数组属性是否为空及指定索引元素是否存在
Swift 结构体数组索引越界的安全检查方案
问题场景
当结构体中包含数组属性时,直接通过索引访问数组元素,在数组为空或索引超出元素数量的情况下会触发索引越界错误,示例代码如下:
struct Item {var name: String} struct Example {var itemArray: [Item]} let newExample = Example(itemArray: []) // 执行此代码会触发索引越界错误 print(newExample.itemArray[0].name)
分场景解决方案
1. 避免空数组越界
如果仅需处理数组为空的情况,直接使用数组的isEmpty属性判断即可:
if !newExample.itemArray.isEmpty { print(newExample.itemArray[0].name) }
2. 检查指定索引是否有效
如果需要判断任意目标索引是否存在(比如数组有2个元素,要访问第3个),可以通过比较索引值和数组的count属性:
let targetIndex = 2 if targetIndex < newExample.itemArray.count { print(newExample.itemArray[targetIndex].name) }
通用优雅方案:扩展安全下标
为了让代码更直观且具备通用性,我们可以给Collection协议扩展一个安全下标,所有遵循该协议的集合类型(包括数组)都能直接使用:
struct Item { var name: String } struct Example { var itemArray: [Item] } let newExample = Example(itemArray: []) extension Collection { subscript (safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } } // 使用安全下标访问,越界时返回nil,不会崩溃 if let newItem = newExample.itemArray[safe: 0] { print(newItem.name) }
内容的提问来源于stack exchange,提问作者Lionel Yu
相关产品推荐
相关产品推荐

