Swift Morse Decoder

Hi, I’m stuck with Morse Decoder where I believe I have my code right but still I get a String error which I cannot solve.

My code:

var englishText = "this is a secret message"

var secretMessage = ".... --- .-- -.. -.--   .--. .- .-. - -. . .-."

// Add your code below 🤫
var letterToMorse = [
  "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: --.."
]

var morseText = ""
for element in englishText {
  if let morseChar = letterToMorse["\(element)"] {
    morseText += morseChar + " "
  } else {
    morseText += "   "
  }
}
print(morseText)

Error:

Morse.swift:37:35: error: cannot subscript a value of type '[String]' with an argument of type 'String'
  if let morseChar = letterToMorse["\(element)"] {
                                  ^
Morse.swift:37:35: note: overloads for 'subscript' exist with these partially matching parameter lists: ((UnboundedRange_) -> ()), (Int), (Range<Int>), (Range<Self.Index>)
  if let morseChar = letterToMorse["\(element)"] {
                                  ^

Any help would be very much appreciated!

Regards,
Fredrik

Hi fredy, I had the same problem. Check ur quotation marks in the letterToMorse dictionary, f.e.:

In ur case its looks like this: :x:

  "a: .-",
  "b: -...",
  "c: -.-.",

the right solution: :white_check_mark:

  "a": ".-",
  "b": "-...",
  "c": "-.-.",

So you don’t have to add all the quote marks individually I’ll leave you with this:

    "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": "--..
1 Like

Thank you!

So simple but yet so hard to find :slight_smile:

I saw that it was also explained in the hint for point 2 which I have checked but did not see, I should have copied that text instead :smiley:

1 Like

I am very happy that it has helped you!

Sometimes this helps me a lot → https://text-compare.com/

Then I wish you a good time with Swift :smiley:

1 Like