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

通过可选绑定在Swift中进行安全(边界检查)数组查找?

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

通过可选绑定在Swift中进行安全(边界检查)数组查找?

Alex的回答为该问题提供了很好的建议和解决方案,但是,我偶然发现了一种更好的实现此功能的方法:

Swift 3.2及更高版本

extension Collection {    /// Returns the element at the specified index if it is within bounds, otherwise nil.    subscript (safe index: Index) -> Element? {        return indices.contains(index) ? self[index] : nil    }}

Swift 3.0和3.1

extension Collection where Indices.Iterator.Element == Index {    /// Returns the element at the specified index if it is within bounds, otherwise nil.    subscript (safe index: Index) -> Generator.Element? {        return indices.contains(index) ? self[index] : nil    }}

感谢Hamish提出了Swift 3解决方案。

迅捷2

extension CollectionType {    /// Returns the element at the specified index if it is within bounds, otherwise nil.    subscript (safe index: Index) -> Generator.Element? {        return indices.contains(index) ? self[index] : nil    }}

let array = [1, 2, 3]for index in -20...20 {    if let item = array[safe: index] {        print(item)    }}


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

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

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