Search code examples
swiftstructxcode8swift-playground

How to check if an instance of a struct is itself an instance of another struct


I have two struct in Swift of the following type and I would like to visualize the values of the array related to the Appartamento struct that were instantiated in the struct Palazzo but my abilities do not allow it. Do you know if it is possible to do it and how? I thought of using Type Casting but I think they only fit into object classes and not structs.

struct Appartamento {
    var interno:        String
    var numeroBagni:    Int
}

struct Palazzo {
   let appartamenti:   [Appartamento]
    let nome:           String
    let indirizzo:      String
}

var appartamenti: [Appartamento] = [
    Appartamento(interno: "1a", numeroBagni: 2),
    Appartamento(interno: "2a", numeroBagni: 1),
    Appartamento(interno: "1", numeroBagni: 2),
    Appartamento(interno: "2", numeroBagni: 1),
]

var palazzi: [Palazzo] = [
      Palazzo(appartamenti: [appartamenti[0], appartamenti[1]],
             nome: "Palazzo Colere",
             indirizzo: "Via Colere, 7"),
      Palazzo(appartamenti: [appartamenti[2], appartamenti[3]],
             nome: "Palazzo Leoni",
             indirizzo: "Via Alberi, 17")]


for palazzo in palazzi {
    print("\(palazzo.nome):")
    for appartamento in appartamenti {
        // ************************************
        if (the apartment is an instance of the palazzo structure then it displays the data appartamento) { // ******************
            print .....
        }
        // ************************************
}

Solution

  • If you want to print the information of the given apartment house use the member appartamenti of Palazzo

    for palazzo in palazzi {
        for appartamento in palazzo.appartamenti { ...