I was making an app that would encode messages using regular ciphers that could be decoded on paper, and I ran into this problem. Picture of error
I'm not sure if you need it, but here is the code it is inside:
func encodeMessage(input:String) -> String {
var output:String
if cipher == "Ceaser/Shift" {
for i in 0..<input.characters.count {
output = output.append(alphabet[seekAlphabet(letter: input[i])])
}
return output
}
}
Another piece of code that might help:
func seekAlphabet(letter:String) -> Int {
for i in 0..<alphabet.count {
if alphabet[i] == letter {
return i
}
}
}
alphabet is just an array that is the alphabet in a series of strings.
Any ideas of why it is doing this? Thanks!
The problem lies on this line:
output = output.append(alphabet[seekAlphabet(letter: input[i])])
The append instance method mutates the original string, it does not return a value with the result. If you would have looked over the docs , you would have seen that it is declared as:
mutating func append(_ other: String)
Here you have two ways to solve this, by replacing
output = output.append(alphabet[seekAlphabet(letter: input[i])])
with either of the following:
output.append(alphabet[seekAlphabet(letter: input[i])])
output = output + alphabet[seekAlphabet(letter: input[i])]
Now, you know that append(_:)
is a mutating function, and
output.append(alphabet[seekAlphabet(letter: input[i])])
is a ()
(a Void
), because it just mutates and does not return anything. Therefore, by trying to assign output
to the append(_:)
method, you try to assign a string to a Void
, which is illegal.
Swift String
class append(_:)
is mutating function and doesn't return anything. Change this line
output = output.append(alphabet[seekAlphabet(letter: input[i])])
to
output.append(alphabet[seekAlphabet(letter: input[i])])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.