[英]how to fix “Cannot subscript a value of type 'ClosedRange<Int>' with an index of type 'Int' in swift”
I wanna prepare a basic number picker timer for my homework but I cannot fix this problem. 我想为我的作业准备一个基本号码选择器计时器,但我无法解决这个问题。
var timer = Timer()
var counter = 0
//let number = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]
let number = 1 ... 60
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return number[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return number.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
label.text = number[row]
}
But it gives this error. 但它给出了这个错误。
Cannot subscript a value of type 'ClosedRange' with an index of type 'Int'
无法使用类型为“Int”的索引下标“ClosedRange”类型的值
您正在创建一个数组,因此您需要在该范围内使用方括号。
let numbers = [1...60]
You need an array of strings [String]
but you declare an integer range ClosedRange<Int>
您需要一个字符串数组
[String]
但您声明一个整数范围ClosedRange<Int>
Create an array from the range and map the items to String
从范围创建数组并将项映射到
String
let number = Array(1...60).map(String.init)
It's recommended to declare arrays in plural form let numbers
我们建议以复数形式来声明数组
let numbers
You can simply do: 你可以简单地做:
let numbers = Array(1...60)
How does this work? 这是如何运作的?
You can explore this yourself. 你可以自己探索一下。 A trick is to add the explicit
init
call: 一个技巧是添加显式
init
调用:
Array.init(1...60)
and then option -click on init
. 然后选择 -click on
init
。 When you do that, you get: 当你这样做时,你得到:
Summary
摘要
Creates an array containing the elements of a sequence.
创建一个包含序列元素的数组。 Declaration
宣言
init<S>(_ s: S) where Element == S.Element, S : Sequence
Discussion
讨论
You can use this initializer to create an array from any other type that conforms to the Sequence protocol.
您可以使用此初始化程序从符合Sequence协议的任何其他类型创建数组。 For example, you might want to create an array with the integers from 1 through 7. Use this initializer around a range instead of typing all those numbers in an array literal.
例如,您可能希望创建一个包含1到7之间整数的数组。在范围内使用此初始值设定项,而不是在数组文字中键入所有这些数字。
let numbers = Array(1...7) print(numbers) // Prints "[1, 2, 3, 4, 5, 6, 7]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.