1

I have a JSON that might contain an array of string elements and I want to save it to a variable. So far I did:

import SwiftyJSON    
(...)
var myUsers = [""]
if(json["arrayOfUsers"].string != nil)
{
    myUsers = json["arrayOfUsers"] //this brings an error
}

The error says:

cannot subscript a value of type JSON with an index of type string

How can I pass this array safely to my variable?

4
  • You check that json["arrayOfUsers"] is a string and then you try to assign this object to an array of strings - it won't work. Please tell us what is json["arrayOfUsers"], is it a string or an array? Commented Apr 7, 2016 at 15:27
  • It is an array of string, something like ["5523533","5gdsgdse","5gdsgsdb9","5432523d"] Commented Apr 7, 2016 at 15:30
  • @zcui93 I wrote myUsers = json["arrayOfUsers"].array but then I'm getting an error cannot assign value of type [JSON] to type [String] Commented Apr 7, 2016 at 15:33
  • It's because you declared myUsers to be [""] AKA [String] Commented Apr 7, 2016 at 15:33

1 Answer 1

2

You have to get the array of Strings that SwiftyJSON has prepared when it parsed your JSON data.

I will use if let rather than != nil like you do in your question, and we're going to use SwiftyJSON's .array optional getter:

if let users = json["arrayOfUsers"].array {
    myUsers = users
}

If for any reason you get a type error, you can explicitly downcast the SwiftyJSON object itself instead of using the getter:

if let users = json["arrayOfUsers"] as? [String] {
    myUsers = users
}

Note that your array of Strings is also not created properly. Do like this:

var myUsers = [String]()

or like hits:

var myUsers: [String] = []

Both versions are equally valid and both create an empty array of strings.

Sign up to request clarification or add additional context in comments.

9 Comments

Ok, one more question - in this case what about the declaration of myUsers? How should I declare it? var myUsers = [""] causes an error of type mismatch :(
var myUsers = [String]() or var myUsers: [String] = []
Hm, that super weird, I'm getting this error after those changes: imgur.com/RU70gLo What might be wrong here?
Try my second solution in the answer, with the downcast.
:) Now it underlines this: json["array... and says Ambiguous reference to member subscript :|
|

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.