Caesar Cipher step 5 and 6

I am not sure what I am doing wrong here, but every time I run this, I get the result of [“hello”]:

var alphabet: [Character] = [“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 secretMessage = [“hello”]

var message = Array(secretMessage)

print(message)

Hi!

Welcome to the forum, for future reference, format your code clicking </> before pasting (it’s easier to troubleshoot).

As for the problem… can you clarify a bit: what are expecting in terms of the result?

The way it looks right now

  • secretMessage = [“hello”]
    and
  • message = Array(secretMessage)

So the secretMessage that is printed is definitely going to correlate to [“hello”]…

1 Like

Sorry here is the code.

var alphabet: [Character] = ["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 secretMessage = ["hello"]

var message = Array(secretMessage)

print(message)

However the behavior we are observing should not happen when using Array() according to step 5:

Currently, secretMessage looks like "hello" , but we want it to be an array instead, like ["h", "e", "l", "l", "o"] , so that we can compare its items with the items of the alphabet array.

Swift comes with a nifty array initializer, Array() , that can convert a text string to an array of Character s:

var secretMessage = "brutus"

var message = Array(secretMessage)
// ["b", "r", "u", "t", "u", "s"]
2 Likes

You actually came up with the answer!! I often do this (have the answer right under my nose).

Note the difference in your two examples

var secretMessage = ["hello"] and var secretMessage = "brutus"

The reason for the different outputs is the fact that one of them is already an array

var secretMessage = ["bread"]
var message = Array(secretMessage)
print(message)
// Output:
// ['bread']

Compare to:

var secretMessage = "bread"
var message = Array(secretMessage)
print(message)
// Output:
// ["b", "r", "e", "a", "d"]

Array() has other nifty tricks:

var lots_of_bread = Array(repeating: "bread", count: 10)
print(lots_of_bread)
// Output
// ["bread", "bread", "bread", "bread", "bread", "bread", "bread", "bread", "bread", "bread"]

One reason I’m drawn to swift is the great documentation they have! It makes it easy to pick up and make stuff happen. Here’s the section on arrays https://developer.apple.com/documentation/swift/array.

2 Likes

Thank you! I have been going back and forth on this countless times. I knew I just needed a fresh set of eyes to help me find the issue

2 Likes