【问题标题】:Find a letter (from an Array) in and Array and then use the index to get a value from another Array在 Array 中找到一个字母(来自一个 Array),然后使用索引从另一个 Array 中获取一个值
【发布时间】:2020-05-18 01:06:00
【问题描述】:

我正在尝试使用下面的 calc 函数来评估一个单词 假设 showLetters = ["S","W","I","F","T"]

所以 S = 1, W = 4, I = 1, F = 4, T = 1 给我一个 wordScore 11....

我使用数组 alphaLetter 来查找字母在字母表中的位置。 我使用找到的字母的索引从 alphaScore 中获取它的值。

 func calcButton() {
    var testWord = ""
    var wordScore = 0

    let alphaLetter = Array("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z")
    let alphaScore = Array ("1,3,2,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10")

    for k in (0...6)
    {
      testWord = testWord + showLetters[k]

      let letterFound = String(showLetters[k])
      *if let index = alphaLetter.firstIndex(of: letterFound) {*

    }


     }           

我正在努力获取索引

我尝试将 letterFound 指定为找到的字母的字符串。然后尝试使用 if let index = alphaLetter.firstIndex(of: letterFound)

但这给了我一个错误 无法将“String”类型的值转换为预期的参数类型“String.Element”(又名“Character”)

所以我有点卡住了......

建议或指导将不胜感激

谢谢

【问题讨论】:

  • 你知道你的数组alphaLetteralphaScore 有逗号作为元素吗?所以你的第一个数组的元素是“A”然后是逗号然后是“B”然后是逗号等等。例如“C”是第五个元素,而不是第三个元素。这真的是你想要的吗? — 此外,元素是字符,而不是字符串。这也是你想要的吗?
  • 啊,这可以解释一些事情。我只需要找到每个字母的值,所以不是 100% 确定最好的方法吗?

标签: arrays xcode swiftui swift5


【解决方案1】:

alphaLetteralphaScore 是字符串。从一个字符串创建数组的结果是[Character],包括逗号!。

可能你的意思是这个(在 Playground 中测试)

let showLetters = ["S","W","I","F","T"]

func calcButton() {
    var testWord = ""
    var wordScore = 0

    let alphaLetter = Array(["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
    let alphaScore = Array ([1,3,2,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10])

    for k in 0..<showLetters.count 
    {
        testWord = testWord + showLetters[k]

        let letterFound = showLetters[k]
        if let index = alphaLetter.firstIndex(of: letterFound) {
            wordScore += alphaScore[index]
        }
    }
    print(wordScore)
}

calcButton()

尽管如此,使用字典["A" : 1, "B" : 3 ...] 效率更高

func calcButton() {
    var testWord = ""
    var wordScore = 0

    let alphaDict =  ["P": 3, "U": 1, "B": 3, "M": 3, "A": 1, "C": 2, "V": 4, "L": 1, "Q": 10, "D": 2, "H": 4, "K": 5, "N": 1, "J": 8, "T": 1, "E": 1, "X": 8, "R": 1, "O": 1, "I": 1, "G": 2, "F": 4, "Y": 4, "Z": 10, "W": 4, "S": 1]

    for character in showLetters {
        if let value = alphaDict[character] {
            wordScore += value
        }
    }
    print(wordScore)
}

【讨论】:

  • 上面的代码给了我同样的错误“无法将'String'类型的值转换为预期的参数类型'String.Element'(又名'Character')”我会看看字典,因为不知道他们。
猜你喜欢
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-23
相关资源
最近更新 更多