arrays - 根据字符串输出引用数组
问题描述
我在这里学习 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)
解决方案
好吧,您可以使用字典,其中键替换数组名称,值是数组。然后,您将使用您创建的名称在字典中查找数组值:
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)
}
推荐阅读
- python - 使用具有两个元组元素的参数创建函数
- python - 如果 browser.find_element_by_xpath 没有数据或无法定位元素时条件不起作用
- flutter - 创建 Firebase 用户不会更新 authStateChanges 方法
- node.js - 使用 react js 从前端上传图像到 Mongo db 时,在控制台中获取不同的端口错误
- reactjs - React 容器模式中的 Formik
- swift - 如何在 2021 年编写一个 Swift String Characters.reverse 函数
- swift - Swift callkit 有时在接到电话后无法激活扬声器(仅限来电)
- java - 从 Java 文件中读取一组数字,设置为 1 到 3、4 到 16
- c++ - 出现错误错误:“b”之前的预期主表达式
- java - 我们如何利用自定义的@Qualifier 方法?