2

The following code does not compile in Swift 2.0

var eventsIds : [CalendarEventLink?] = [CalendarEventLink?](count: 5, repeatedValue: nil)
var data = try NSJSONSerialization.dataWithJSONObject(eventsIds, options: [])

I'm getting error:

'[CalendarEventLink?]' is not convertible to '[AnyObject]'

How can I serialise array to json in swift?

3
  • 1
    [CalendarEventLink?](count: 5, repeatedValue: nil) creates an array of 5 x nil: [nil, nil, nil, nil, nil], but you can't encode nil into JSON. Commented Oct 9, 2015 at 16:09
  • You have to be able to unwrap this in order for it to be serializable. You can try it with an if...let to decide if it is not an optional. Commented Oct 9, 2015 at 16:23
  • So basically, you say that the elements of an swift array must be not optional to be able to used as json object? Commented Oct 9, 2015 at 21:46

1 Answer 1

1
var eventsIds : [CalendarEventLink] = []
var data = try NSJSONSerialization.dataWithJSONObject(eventsIds, options: [])

As mentioned in comments above, you can't send array of optional items into [AnyObject]

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

Comments

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.