【问题标题】:How to check if an instance of a struct is itself an instance of another struct如何检查结构的实例本身是否是另一个结构的实例
【发布时间】:2019-12-27 04:30:57
【问题描述】:

我在 Swift 中有两个以下类型的结构,我想可视化与在 Palazzo 结构中实例化的 Appartamento 结构相关的数组的值,但我的能力不允许这样做。你知道是否可以做到以及如何做到这一点?我想过使用类型转换,但我认为它们只适合对象类而不适合结构。

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 .....
        }
        // ************************************
}

【问题讨论】:

  • 打印palazzo.appartamenti怎么样?
  • 有时最简单的解决方案会失控......谢谢

标签: swift struct xcode8 swift-playground


【解决方案1】:

如果您想打印给定公寓的信息,请使用Palazzo的成员appartamenti

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

【讨论】:

  • 这就是解决方案。谢谢
  • 确实其他问题都没有解决(除了一个会确认的问题)...
猜你喜欢
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多