栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Swift中捕获“索引超出范围”?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Swift中捕获“索引超出范围”?

正如评论和其他答案中所建议的那样,最好避免这种情况。但是,在某些情况下,您可能需要检查数组中是否存在某个项目以及是否确实将其返回。为此,您可以使用下面的Array扩展名来安全地返回数组项。

迅捷3

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

迅捷2

extension Array {    subscript (safe index: Int) -> Element? {        return indices ~= index ? self[index] : nil    }}
  • 这样你永远 不会打
    Index out of range
  • 您必须检查项目是否为
    nil

当我让ar = [1,3,4],然后让v = ar [5]时,在Xpre
8.3.2的Playground中尝试Swift3代码仍然会导致“崩溃”。为什么?–托马斯·滕佩尔曼5月17日17:40

你必须使用我们定制的标所以不是

let v = ar[5]
,它是无线本地环路
let v = ar[safe: 5]

从数组默认获取值。

let boo = foo[index]

添加使用自定义下标。

let boo = fee[safe: index]// And we can warp the result using guard to keep the pre going without throwing the exception.guard let boo = foo[safe: index] else {  return}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448319.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号