SH10151 SH10151 - 4 months ago 8
iOS Question

Trouble instantiating an object via init() method passing in an Array of Dictionaries

I'm using Swift to create an NSObject by its init() method, passing in strings and an array of Dictionaries (the Dictionaries represent UIButtons, each with a title, a link, a blurb for each potential button - there can be from 1-3 of these buttons).

In the init() method of ContentItem() I'm trying to create Dictionaries as properties of this object.

It is giving me an error: "Instance member 'subscript' cannot be used on type "(String: String)" on the line: "var tempButton = [String: String][]".

I did some research and it sounds like it might be to do with instantiating variables in the init() method - because this is before the object has been created?

Is this correct? Anyone have any insight into this? Is there a way to just map these passed in arguments to the class? I'm stuck. Thanks.

class ContentItem: NSObject {
var title: String
var body: String
var buttonsArray: Array<Dictionary<String,String>>

init?(title: String, body: String, buttonsArgs: Array<Dictionary<String, String>>) {
self.title = title
self.body = body

for btn in buttonsArgs {
var tempButton = [String: String][] // placeholder for the button we are creating to attach to buttonsArray[]
for (btnKey, btnValue) in btn { // iterate through each button's Dictionary element that is passed in to init()
print("btnKey: \(btnKey), btnValue: \(btnValue)")
tempButton[btnKey] = btnValue // assembling the parameters of this button
}
self.buttonsArray.append(tempButton) // assigning the buttons to the object
}
super.init()
}
}

Answer

Issue 1

Function calls are always done with the ( ), not [ ]:

var tempButton = [String: String]()

Which is equivalent to:

var tempButton Dictionary<String, String> = Dictionary<String, String>.init()

Issue 2

You're attempting to append to an array that doesn't exist:

var buttonsArray: Array<Dictionary<String,String>>

That line declares that a variable called buttonsArray will exist, of type Array<Dictionary<String,String>>, but it doesn't define any values for it. Change it to this instead:

var buttonsArray: Array<Dictionary<String,String>> = Array<Dictionary<String,String>>()

And now that there is an initialization occuring, the compiler can infer the type for us:

var buttonsArray = Array<Dictionary<String,String>>()

And we can use the shorthand for Array<Dictionary<String,String>>, [[String : String]];

var buttonsArray = [[String : String]]()
Comments