【问题标题】:Cannot subscript a value of type [uiButton] with an index of type 'UIButton' (Swift)无法使用类型为“UIButton”的索引下标类型为 [uiButton] 的值(Swift)
【发布时间】:2020-11-17 00:58:50
【问题描述】:

我有一个 UIButton radioController.buttonsArray = [ button1, button2, button3 ] 数组,并希望通过将选定按钮传递给函数 radioController.defaultButton = radioController.buttonsArray[selectedButton] 来设置选定按钮的默认值

我想用一个字符串(本来是一个整数,但是数组中的位置随着设计不断变化),所以在这上面,我尝试了:

var selectedButton: UIButton = button1
switch currentSelection {
    case "selection 1" : selectedButton = button1
    case "selection 2" : selectedButton = button2
    case "selection 3" : selectedButton = button3
    default: 
        break
} 

我首先收到错误消息:可选类型“[UIButton]?”的值必须解包以引用已包装的基本类型“[UIButton]”的成员“下标”

但在“修复”它之后((使用?或!)我收到消息:
无法使用“UIButton”类型的索引为 [uiButton] 类型的值下标

如何声明 selectedButton 来执行此操作?还是有更好的办法?

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    您只能使用Ints 为数组下标。如果要查找数组中特定元素的索引,则应在数组上使用firstIndex(of:) 函数。

    但是,对于您的特殊需求,似乎根本没有理由访问该数组,因为您已经可以访问所需的元素。

    你可以做radioController.defaultButton = selectedButton

    【讨论】:

    • 谢谢!有时我只见树木不见森林。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2017-03-19
    • 2020-02-08
    • 2016-11-04
    相关资源
    最近更新 更多