将多个值归因于Swift

时间:2015-09-04 06:22:52

标签: swift

我想问一下如何将多个值归因于同一个键然后使用那些(相同)键(来自多个值)。 练习来自https://www.weheartswift.com/dictionaries/ 它只是改编了他的代码。

我首先使用一个键的多个值创建这样的字典:

      var code = [
    "X" : "a","b",
    "Y" : "c","d",
    "Z" : "e","f",

...
]

然后,当我输入包含b c d e或f的单词时,它会根据字典将这些字母更改为X Y或Z

var encodedMessage = "abcdef"

var decoder: [String:[String]] = [:]

// reverse the code
for (key, value) in code {
    decoder[value] = key
}

//an error occurs here, what can i do to fix it?

var decodedMessage = ""

for char in encodedMessage {
    var character = "\(char)"

    if let encodedChar = decoder[character] {
        // letter
        decodedMessage += encodedChar
    } else {
        // space
        decodedMessage += character
    }
}

因为我更喜欢解码消息而没有划分"字母"和"空间"还有更好更简单的方法吗? 所以它就像是,空间"

println(decodedMessage)

我希望decodeMessage是XXYYZZ

非常感谢那些可以提供帮助的人。 此致

1 个答案:

答案 0 :(得分:0)

下面:

let encodedMessage = "abcdef"

var code = ["X": ["a", "b"], "Y": ["c", "d"], "Z": ["e", "f"]]

var decoder: [String:String] = [:]

// reverse the code
for key in code.keys {
    for newCode in code[key]! {
        decoder[newCode] = key
    }
}


var decodedMessage = ""

for char in encodedMessage.characters {
    var character = "\(char)"

    if let encodedChar = decoder[character] {
        // letter
        decodedMessage += encodedChar
    } else {
        // space
        decodedMessage += character
    }
}

您只需将它们存储为数组。