[英]Cannot subscript a value of type [uiButton] with an index of type 'UIButton' (Swift)
I have an array of UIButton radioController.buttonsArray = [ button1, button2, button3 ]
and would like to set the default to the selected button by passing the selected button to a function radioController.defaultButton = radioController.buttonsArray[selectedButton]
我有一个 UIButton
radioController.buttonsArray = [ button1, button2, button3 ]
数组,并希望通过将所选按钮传递给 function radioController.defaultButton = radioController.buttonsArray[selectedButton]
来设置所选按钮的默认值
I want to use a string (originally was an integer, but the position in the array kept changing with the design), so above this, I tried:我想使用一个字符串(最初是一个 integer,但是数组中的 position 随着设计不断变化),所以在此之上,我尝试了:
var selectedButton: UIButton = button1
switch currentSelection {
case "selection 1" : selectedButton = button1
case "selection 2" : selectedButton = button2
case "selection 3" : selectedButton = button3
default:
break
}
I first get the error message: Value of optional type '[UIButton]?'我首先收到错误消息:可选类型“[UIButton] 的值?” must be unwrapped to refer to member 'subscript' of wrapped base typ '[UIButton]'
必须解包以引用已包装的基本类型“[UIButton]”的成员“下标”
but after "fixing" it ((with either? or:) I get the message:但是在“修复”它之后((使用任何一个?或:)我收到消息:
Cannot subscript a value of type [uiButton] with an index of type 'UIButton'无法使用“UIButton”类型的索引为 [uiButton] 类型的值下标
How do I declare selectedButton to do this?我如何声明 selectedButton 来做到这一点? Or is there a better way?
或者,还有更好的方法?
You can only subscript arrays with Int
s.您只能使用
Int
为 arrays 下标。 If you want to find the index of a specific element in an array, you should use the firstIndex(of:)
function on the array.如果要查找数组中特定元素的索引,则应使用数组上的
firstIndex(of:)
function。
However, for your particular needs it seems there's no reason to access the array at all, since you already have access to the element you need.但是,对于您的特定需求,似乎根本没有理由访问该数组,因为您已经可以访问所需的元素。
You can just do radioController.defaultButton = selectedButton
.你可以做
radioController.defaultButton = selectedButton
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.