如果索引超出范围,则提供捕获(Swift 5)[已关闭]

slmsl1lt  于 2022-12-28  发布在  Swift
关注(0)|答案(4)|浏览(139)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

两年前关闭了。
Improve this question
当我在Swift中通过GET方法获取数据时,它显示为一个Array:

URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in

                guard let data = data else { return }
                do {

                    let obj: Response = try JSONDecoder().decode(Response.self, from: data)

                    let cit = obj.assetProfile?.city
                    let coun = obj.assetProfile?.country
                    let negociosLocacion = ("\(cit ?? "N/A"), \(coun ?? "N/A")")

                    let object = EObject(marketOpen: (obj.price?.regularMarketOpen?.fmt ?? "N/A"))

                    self.e.append(object)

但是,我如何创建一个catch方法,如果索引超出范围,将显示一个segue,例如,不崩溃的应用程序?

gajydyqb

gajydyqb1#

在访问数组之前,可以使用indices检查数组是否包含索引:

guard myArray.indices.contains(1) else { return }
let value = myArray[1]

Apple文档:indices

svujldwt

svujldwt2#

你可以通过各种方式来处理它,例如我在下面给你看一些代码片段,看看哪种情况与你的相似。
1.如果你从数组中按索引获取项目,那么你可以避免数组索引超出范围的错误,如:

if yourIndex <= yourArray.endIndex {
    //Then do your desired operation by getting items by your index            
} else {
    //Do not get items by your index because it is out of range. 
    //Do anything else            
}

1.您可以检查数组是否为空,例如:

if yourArray.isEmpty {
    // Don't do any array item get operations because your array is empty           
} else {
    // Your array is not empty
}

1.你可以检查你的数组是否至少有固定数量的元素,比如:

if yourArray.count >= yourDesiredNumberOfElements {
    // Your array have at least your desired number of elements.
} else {
    // Your array does not have your desired number of elements.
    // your array has less elements than you desire.
}
2izufjch

2izufjch3#

一个好的解决方案是使用一个带有return可选元素的安全下标。

extension Array {
    public subscript(safeIndex index: Int) -> Element? {
        guard index >= startIndex, index < endIndex else {
            return nil
        }

        return self[index]
    }
}
bn31dyow

bn31dyow4#

为了检查索引是否超出界限从而不导致应用崩溃并以另一种方式处理这种情况,

if (yourArray.count - 1) >= yourIndex {
   //Not out of bounds, carry on.
} else {
   //This is when your app would crash due to being out of bounds.
}

相关问题