首页 > 解决方案 > 根据字符串输出引用数组

问题描述

我在这里学习 Swift,如果这是一个愚蠢的问题,我深表歉意。

我正在寻找使用一个函数(字符串)的输出来确定不同函数(数组)的输入。

然后将第一个函数输出(字符串)与另一个字符串组合以形成已定义数组的名称,我想将其用作第二个函数的输入。但是,尽管名称相同,但 String 不被视为数组。

我跳过了一些代码,但下面的相关部分。

// Defined array
let rushProb = [0,11,19,64,78,89,96,98,99,100]

// Define probability and outcome function - PlayType
func findPlay(prob: [Int], outcome: [String]) -> String {
    if let index = prob.firstIndex(where: { $0 > Int.random(in: 1...100) }) {
        return outcome[index]
    }
    else {
        return "na"
    }
}

// This is successfully output as "rush"
let playSel = findPlay(prob: scen1Prob, outcome: scenPlay)

// This then creates "rushProb"
let playSelProb = playSel+"Prob"

// I want this to ultimately be findYards(prob: rushProb)
findYards(prob: playSelProb)

标签: arraysswift

解决方案


好吧,您可以使用字典,其中键替换数组名称,值是数组。然后,您将使用您创建的名称在字典中查找数组值:

let arrays = ["rushProb": [0,11,19,64,78,89,96,98,99,100],
              "fooProb" : [0,15,29,44,68,78,86,92,94,100]]

// This is successfully output as "rush"
let playSel = findPlay(prob: scen1Prob, outcome: scenPlay)

// This then creates "rushProb"
let playSelProb = playSel+"Prob"

// look up the array that corresponds to "rushProb"
if let array = arrays[playSelProb] {
    findYards(prob: array)
}

推荐阅读