Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 斯威夫特:使用enum';从常量数组访问UIButton和字符串的原始值?_Arrays_Swift_Enums_Uibutton_Constants - Fatal编程技术网

Arrays 斯威夫特:使用enum';从常量数组访问UIButton和字符串的原始值?

Arrays 斯威夫特:使用enum';从常量数组访问UIButton和字符串的原始值?,arrays,swift,enums,uibutton,constants,Arrays,Swift,Enums,Uibutton,Constants,我提前道歉,这很难解释。如果需要,我会提供更多细节 这是常量结构,我用来引用集合数组中的UIButtons,并用作字典的键 struct Constants { static let scoreA = "score_a" static let scoreB = "score_b" static let scoreC = "score_c" static let scoreD = "score_d" static let constantsArray =

我提前道歉,这很难解释。如果需要,我会提供更多细节

这是常量结构,我用来引用集合数组中的
UIButtons
,并用作字典的键

struct Constants {
    static let scoreA = "score_a"
    static let scoreB = "score_b"
    static let scoreC = "score_c"
    static let scoreD = "score_d"


    static let constantsArray = [kScoreA, kScoreB, kScoreC, kScoreD]
    enum Scores: Int, CaseIterable { case scoreA = 1, ScoreB, ScoreC, ScoreD}
}
我的初始视图控制器有许多
ui按钮
。所有得分按钮都从1开始标记。
ui按钮
连接到ibui按钮阵列。这样我就可以避免有太多的iboutlet

@IBOutlet var collectionOfScoreButtons: Array<UIButton>!
UIButtons的顺序与枚举的顺序相同,例如scoreA是枚举中的第一项,scoreA button是数组中的第一个按钮

我可以像这样检索字典键,这样我就可以更新它的值

// after pushing a score button
func handleScoreValue(tag: Int) {
     let scoreKey = Constants.constantScoreArray[tag - 1]
     dictionary[scoreKey, default: 0] += 1
}

我不确定是否有更好的方法来处理这种情况。代码运行良好,但我觉得有更好的方法。

为什么不直接使用
enum

enum Constants: String, CaseIterable {
    case scoreA = "score_a"
    case scoreB = "score_b"
    case scoreC = "score_c"
    case scoreD = "score_d"
}
因此,您可以循环遍历枚举案例,如

Constants.allCases[anyIndex].rawValue

我看不出使用
分数
枚举
来获取某些按钮的引用有什么好处,您必须指定索引

if let scoreAButton = collectionOfScoreButtons[0]
此外,您还可以将
常量设置为
enum
并实现
CaseIterable
协议,该协议允许您使用
enum.allCases创建所有
enum
案例的数组

enum Score: String, CaseIterable {
    case A = "score_a"
    case B = "score_b"
    case C = "score_c"
    case D = "score_d"
}
然后我相信您的按钮有iAction,这样您就可以在按钮数组中获得
发送者的索引。这样您就不必设置
ui按钮的
tag

@IBAction func buttonPressed(_ sender: UIButton) {
    if let index = collectionOfScoreButtons.index(of: sender) {
        handleScoreValue(index: index)
    }
}
最后,对于
allCases
数组中的某个索引,您可以将
scoreKey
作为案例的
rawValue

func handleScoreValue(index: Int) {
    let scoreKey = Score.allCases[index].rawValue
    dictionary[scoreKey, default: 0] += 1
}

让我试一试。这看起来应该行得通。我建议在几乎所有情况下都不要使用标签。相反,创建一个子类
UIButton
,并添加必要的标识信息(枚举值、委托等)。不要摆弄原始整数值,你只是在乞求错误,谢谢。此外,我觉得我在这里被宠坏了,因为你没有设置标签。非常感谢你。
func handleScoreValue(index: Int) {
    let scoreKey = Score.allCases[index].rawValue
    dictionary[scoreKey, default: 0] += 1
}