Swift Array - 检查索引是否存在 [英] Swift Array - Check if an index exists

查看:38
本文介绍了Swift Array - 检查索引是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,有没有什么方法可以在不抛出致命错误的情况下检查数组中是否存在索引?

In Swift, is there any way to check if an index exists in an array without a fatal error being thrown?

我希望我能做这样的事情:

I was hoping I could do something like this:

let arr: [String] = ["foo", "bar"]
let str: String? = arr[1]
if let str2 = arr[2] as String? {
    // this wouldn't run
    println(str2)
} else {
    // this would be run
}

但我明白

致命错误:数组索引超出范围

fatal error: Array index out of range

推荐答案

Swift 中的优雅方式:

An elegant way in Swift:

let isIndexValid = array.indices.contains(index)

这篇关于Swift Array - 检查索引是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆