class Character { type: String name: String } class Hero : Character { power: String } class Princess : Character { kingdom: String } class Civilian : Character { } ... struct Model { characters: [Character] }
// Type checking if model.characters[indexPath.row] is Hero { print(model.characters[indexPath.row].name) } // Type checking and Typecasting if let hero = model.characters[indexPath.row] as? Hero { print(hero.power) }
利用结构体和协议
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
protocol Character { var type: String { get set } var name: String { get set } } struct Hero : Character { power: String } struct Princess : Character { kingdom: String } struct Civilian : Character { } ... struct Model { characters: [Character] }
// Type checking if model.characters[indexPath.row] is Hero { print(model.characters[indexPath.row].name) } // Type checking and Typecasting if let hero = model.characters[indexPath.row] as? Hero { print(hero.power) }
enum Character { case hero(Hero) case princess(Princess) case civilian(Civilian) } ... switch characters[indexPath.row] { case .hero(let hero): print(hero.power) case .princess(let princess): print(princess.kingdom) case .civilian(let civilian): print(civilian.name) }