0

I'd like to create a class instance within an array declaration. How is that done?

Something similar to the following:

myclassA.myarray = [ClassB() {name="Cleaning", deptId=12}, ClassB() {name="Repairs", deptId=30]

Where the array type is:

class ClassB : NSObject {
  var name:String?
  var deptId:Int?
}

1 Answer 1

2

Your array type would be ClassB. You also have to create an initializer for your ClassB. Example:

class ClassB: NSObject {
    var name:String?
    var deptId:Int?
    init(name: String, deptId: Int) {
        self.name = name
        self.deptId = deptId
    }
}

class ClassA {
    var myarray:[ClassB] = []
}

let myclassA = ClassA()

myclassA.myarray = [ClassB(name: "Cleaning", deptId: 12), ClassB(name: "Repairs", deptId: 30)]
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.