Fatal Error: Index out of Range / UIPickerView /Array/ Swift

Fatal Error: Index out of Range / UIPickerView /Array/ Swift

我的 UIPickerView 有四个组件,当我尝试构建它时,它会返回给我。我该怎么办我的意思是我将行数增加了一个点,因为在 Swift 中数字从 0 开始但没有任何效果.... 有什么问题?

let componentOne = [1...1000]
    let componentTwo = [1...59]
    let componentThree = [1...59]
    let componentFour = [1...10]
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 4
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 1000
        }
        if component == 1 {
            return 59
        }
        if component == 2 {
            return 59
        }
        if component == 3 {
            return 10
        }
        return component
    }
        
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            _ = componentOne[row]
            return "\(1000)"
            }
            if component == 1 {
                _ = componentTwo[row]
                return "\(59)"
                }
                if component == 2 {
                    _ = componentThree[row]
                    return "\(59)"
                    }
                    if component == 3 {
                        _ = componentFour[row]
                        return "\(10)"
                        }
        return nil
                    }
    

请考虑 [1...10] 一个 范围的数组,而不是 10 个整数的数组。

你必须写

let componentOne = Array(1...1000)
let componentTwo = Array(1...59)
let componentThree = Array(1...59)
let componentFour = Array(1...10)

为避免这些错误,请不要对 numberOfRowsInComponent 的 return 值进行硬编码。

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    switch component {
        case 0: return componentOne.count
        case 1: return componentTwo.count
        case 2: return componentThree.count
        case 3: return componentFour.count
        default: return 0
    }

}