Search code examples
arraysswiftstructureinitializing

Newbie: referencing and initializing structure elements within structures


OK, super-newbie Swift learner here with what I am sure is a simple question, that for some reason I cannot wrap my head around.

In the below code, I am creating a (very) simple address book structure just to understand how to reference and initialize the various elements, especially structures within structures. What am I doing wrong and is there a better way to write this? I am getting errors (using Swift Playground).

Errors on the last three lines:

Instance member 'page' cannot be used on the type 'AddressBookStruct'
Instance member 'subscript' cannot be used on type '[AddressPageStruct]'.

Plus, when I set var page = [AddressBookStrcut] I get the error:

Expected member name or constructor call after type name

Thanks in advance for the understanding nudge. :)

struct AddressPageStruct {
    let firstName: String
    let lastName: String
    let cellPhone: Int

    init(f: String, l:String, c:Int) {
        firstName = f
        lastName = l
        cellPhone = c
    }
}

struct AddressBookStruct {
    let color: String
    let size: String
    var page = [AddressPageStruct]
}

var littleBlackBook = AddressBookStruct.self

littleBlackBook.init(color: "Black", size: "Little")

littleBlackBook.page[0].cellPhone = 6191234567
littleBlackBook.page[0].firstName = "Bob"
littleBlackBook.page[0].lastName = "Smith"

Solution

  • The struct is value type, please check this. structure vs class in swift language,

    you can't make this littleBlackBook.page[0].cellPhone, because cellPhone is constant you use let, instead use the constructor, also I change the page for empty array of AddressPageStruct

    import Cocoa
    
    struct AddressPageStruct {
        let firstName: String
        let lastName: String
        let cellPhone: Int
    
        init(f: String, l:String, c:Int) {
            firstName = f
            lastName = l
            cellPhone = c
        }
    }
    
    struct AddressBookStruct {
        let color: String
        let size: String
        var page = [AddressPageStruct]()
    }
    
    var littleBlackBook = AddressBookStruct(color: "Black", size: "Little")
    
    littleBlackBook.page.append(AddressPageStruct(f: "Bob", l: "Smith", c: 6191234567))
    print(littleBlackBook.page)