0

I have the following array in Swift:

var words = [
        "English" : ["Hello", "Bye"],
        "Spanish" : ["Hola", "Adios"]
    ]

How can I get the value for index, something as the following doesn't work

print(words["English"][0])

It throws the error: Value of optional type Array? not unwrapped, did you mean to use ! or ? but that just makes it:

print(words["English"]?[0])

and still doesn't work, please help.

5
  • It looks fine. what's the problem? Commented Jul 25, 2017 at 1:20
  • Define "doesn't work". Commented Jul 25, 2017 at 1:20
  • Does the error disappear changing the ? to a !? Commented Jul 25, 2017 at 1:22
  • @rmaddy - Yeah, I realized that and deleted my comment. OP really needs to define "still doesn't work". :) Commented Jul 25, 2017 at 1:23
  • you want the values under English ? Commented Jul 25, 2017 at 5:08

1 Answer 1

1

You need to look into how to unwrap optionals. For example, what you are trying to do could be done either of these two ways:

Force unwrapping:

print(words["English"]![0])

Safe unwrapping:

if let hello = words["English"]?[0]{
    print(hello)
}
Sign up to request clarification or add additional context in comments.

1 Comment

print(words["English"]![0]) worked. Thank you @WMios

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.