简体   繁体   中英

Swift : protocol extension and arrays

I have some struct objects that are heterogeneous like this

struct Cat: Hashable {
   let name: String
   let catId: Int
}
struct SubCat: Hashable {
   let name: String
   let catId: Int
   let parentCatId: Int
}

Now I have a tableView that needs to show either Cat or SubCat. My first choice was to extend both classes with a protocol :

protocol Selectable {
    func asString() -> String
}

and my struct became :

struct Cat: Hashable, Selectable {
   let name: String
   let catId: Int
   func asString() -> {
      return self.name
  }
}
struct SubCat: Hashable, Selectable {
   let name: String
   let catId: Int
   let parentCatId: Int
   func asString() -> {
      return self.name
  }
}

It worked so far. I declared a [Selectable] object in my TableViewController, used asString() to populate my cells. Compiled like a charm.

But here's the thing. I've got a CatModel class and a SubCatModel class, each returning an array of each structs [Cats] and [SubCats] When I try to assign the [Cat] array to the [Selectable] array, it does not compile. If I changed the return type of my [Cat] array to [Selectable], it does not compile.

Can anyone help me with this? I guess I'm missing something here. Thanks.

Cat数组映射到Selectable数组:

let selectableArray = catArray.map { $0 as Selectable }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM