0

The array contained in the key "children" contains 100 items.

Is there away to tell SwiftyJSON to grab a random index? I tried creating a random number

var random = arc4random_uniform(24)

but when I inserted random I got the error:

"Cannot subscript a value of type 'JSON' with an index of type 'UInt32'"

I also converted it to an NSNumber and same thing, I'm completely lost.

func getBackgoundImageData(completed: @escaping DownloadComplete) {

    let imageURL = URL(string: IMAGE_URL)!
    Alamofire.request(imageURL).responseJSON { response in

        switch response.result {

        case .success(let value):

            let json = JSON(value)
            if let url = json["data"]["children"][0]["data"]["preview"]["images"][0]["source"]["url"].string {
                self._backgroundImageURL = url
            }

        case .failure(let error):
            print(error)
        }
        completed()
    }   
}
1
  • In general when you use something like ["data"]["children"][0]["data"]["preview"]["images"][0]["source"]["url"] you are going to have problems as Swift may not be able to infer the types of all those access correctly. Split this line out into a series of conditional downcasts if let data = json["data"] as [String:Any] ... and so on until you get your final array and then use the random index on that Commented Dec 1, 2016 at 0:01

1 Answer 1

1

The arc4random_uniform function's input and returned value are both UInt32. Swift is picky about numeric types, and does not silently convert between them like C family languages do. You should cast random ego an Int:

var random = Int(arc4random_uniform(24))

(And you need to break up your indexing into your data structure as Paul says in his comment.)

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

2 Comments

giddy up! honestly I thought I had attempted to cast it as an Int && NSNumber && pretty much any number format...thanks bud :)
NSNumber is an artifact of the fact that the numeric types are not objects in Objective-C. You can't put numeric values into an NSArray without converting them to NSNumbers. There is no real reason to use NSNumbers in Swift.

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.