swift - 如何修复未解析的标识符错误并正确调用 Swift 中的函数?

标签 swift dictionary

我刚开始使用 Swift,刚刚收到第一份作业。赋值指令如下: 使用数组类的map函数将整数数组转换为整数表示的字。例如,如果您的数组是:[49],则生成的数组应该类似于:[“四十九”]。该映射至少应处理数千个数字。

我收到了许多错误,但我无法弄清楚的最大错误是: main.swift:46:25:错误:使用未解析的标识符“randomArray” 让 stringRandomArray = randomArray.map{convertInt(num: $0)}

除此之外,我在 switch 语句中的函数调用中遇到错误。如何以变量作为参数快速调用函数?我知道我的代码非常困惑,但我仍在适应新语言。

let singleDigit = [0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]
let doubleDigit = [11: "Eleven", 12: "Twelve", 13: "Thirteen", 14: "Fourteen", 15: "Fifteen", 16: "Sixteen", 17: "Seventeen", 18: "Eighteen", 19: "Nineteen"]
let tensMultiples = [10: "Ten", 20: "Twenty", 30: "Thirty", 40: "Fourty", 50: "Fifty", 60: "Sixty", 70: "Seventy", 80: "Eighty", 90: "Ninety"]
let hundreds = [100: "Hundred"]
let thousands = [1000: "Thousand"]


func convertInt(num: Int) -> String{
var length = num.count
var output = ""
    switch length {
        case 1:
            calculateOne(num)
        case 2:
            calculateTwo(num)
        case 3:
            calculateThree(num)
        case 4:
            calculateFour(num)
    }
}

func calculateOne(num: Int) -> String {
    return singleDigit[num]
}

func calculateTwo(num: Int) -> String {
    if num > 10 && num < 20 {
        return doubleDigit[num]
    } else if num % 10 == 0 {
        return tensMultiples[num]
    } else {
        return tensMultiples[num / 10] + doubleDigit[num % 10]
    }
}

func calculateThree(num: Int) -> String {
    return singleDigit[num / 100] + hundreds[100] + calculateTwo[num % (singleDigit[num / 100] + hundreds[100])]
}

func calculateFour(num: Int) -> String {
    return singleDigit[num / 1000] + thousands[1000] + calculateThree[num % (singleDigit[num / 1000] + thousands[1000])]
}

let stringRandomArray = randomArray.map{convertInt(num: $0)}

最佳答案

I cannot figure out is: main.swift:46:25: error: use of unresolved identifier 'randomArray' let stringRandomArray = randomArray.map{convertInt(num: $0)}

这个错误是由于程序中没有声明这样的变量引起的。 您需要首先创建一个数组,然后使用函数将其整数值映射到字符串值。对于这个例子,我只是硬编码了“随机”数组:

let randomArray = [5, 42, 94, 3, 12]
let stringRandomArray = randomArray.map { convertInt(num: $0) }

在学习新语言时,生成随机整数数组本身就是一项有趣的任务,因此我只是使用了一个更简单的版本并在脑海中生成了随机数:)

How do you call a function in swift with a variable as the argument?

您只需在括号内传递变量名称即可:

func triple(value: Int) -> Int {
    return value * 3
}

var n = 10
let nTimesThree = triple(value: n) //nTimesThree is now 30

我还强烈建议阅读 Swift Programming Language Guide 。它很好地介绍了许多语言特性,包括函数。祝学习愉快!

关于swift - 如何修复未解析的标识符错误并正确调用 Swift 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60021296/

相关文章:

swift - AnyCancellable.store(在:) with Combine

ios - TableView 在 Xcode Swift 4 中留有边距

arrays - 带范围的快速开关

python - 递归修改字典

python - 将元组列表转换为字典

ios - 当 Realm 上的对象失效时该怎么办

swift - 异步函数调用与无主对象的取消初始化发生冲突

python - 将一个键值从字典列表转换为列表

android - 更改几乎准备就绪的 Android 应用程序的目标

java - 在二维数组中生成世界地图