0

最终目标:将整数变成书面长手。

我已经看到了一些关于这方面的讨论,这些讨论超出了我的想象。我遇到过可以愉快地分解字符串并打印出字符的函数,但在数组中捕获它们似乎是不可能的。

似乎可以通过下标访问单个字符,但不能对其进行操作。

如果我删除注释,以下将打印出 1,2,9,.,5,0 但是当我运行 if 循环时,我得到了写入的数字字符串,但顺序错误。

let sentence = "129.50"
for (character) in sentence {
  //  print(character)
        if character == "0" {
        print("zero")
    }
        if character == "1" {
            print("one")
    }
        if character == "2" {
        print("two")
    }

                etc etc

我还尝试通过一个函数访问索引函数,尽管每次它总是在最后崩溃时完整打印出来。

func speakNum(_ num:Int) {
    let strgNum = String(num)
    for t in 0...strgNum.count {
        let index = strgNum.index(strgNum.startIndex, offsetBy:t)
        //strgnum.index(strgNum.startIndex, offsetBy:t)
      print(String(strgNum[index]))
    }
}

任何帮助表示赞赏。

4

3 回答 3

1

尝试这个

    let str = "129.50"
    let array = Array(str)
    print(array)

打印 ["1", "2", "9", ".", "5", "0"]

于 2018-09-03T00:58:15.297 回答
1

这是您学习 TDD 的绝佳时机。测试驱动开发。从一个简单的案例开始,你能想到的最简单的...

assert(writtenOut("1") == "one")

完成上述工作,然后添加另一个测试:

assert(writtenOut("1") == "one")
assert(writtenOut("2") == "two")

对所有数字和小数执行上述操作。您还应该处理错误情况:

assert(writtenOut("d") == "")

然后尝试更复杂的事情:

assert(writtenOut("12") == "one two") // or do you want "twelve" in this case?

你可以自己做这件事,从小处着手,然后一路向上。当你完成时,你将拥有一个工作函数和一大堆证明它有效的测试。

于 2018-09-03T00:14:13.887 回答
0

感谢大家的反馈,我最终得到了这个看起来有点麻烦但确实有效的方法:

func radio(_ MHz:Double){
let sentence = String(MHz)
    for (character) in sentence {
            if character == "0" {
                print("zero", terminator:" ")
        }
            if character == "1" {
                print("one", terminator:" ")
        }
            if character == "2" {
                print("two", terminator:" ")
        }
            if character == "3" {
                print("tree", terminator:" ")
        }
            if character == "4" {
                print("fower", terminator:" ")
        }
            if character == "5" {
                print("fife", terminator:" ")
        }
            if character == "6" {
                print("six", terminator:" ")
        }
            if character == "7" {
                print("seven", terminator:" ")
        }
            if character == "8" {
                print("eight", terminator:" ")
        }
            if character == "9" {
                print("niner", terminator:" ")
        }
            if character == "." {
                print("decimal", terminator:" ")
        }
    }
    print()
    print()
}

因此 radio(118.65) 产生

十进制一一八

于 2018-09-03T08:28:55.057 回答