我有两个UICollectionView's
,并且正在将唯一类型的数据(猫,狗)传递到同一UIViewController
。两种类型都有独特的属性,例如imageUrl,性别,年龄等。将这些数据填充到“文本视图”中的最佳方法是什么?
fileprivate var isDog = false
var detailsData: Any? {
didSet {
if detailsData is Dog {
isDog = true
} else if detailsData is Cat {
isDog = false
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
isDog ? fillDogInfo(detailsData: detailsData as! Dog) : fillCatInfo(detailsData: detailsData as! Cat)
}
fileprivate func fillDogInfo(detailsData: Dog) {
contactButtonOutlet.isHidden = false
// Short Info
if let name = detailsData.name {
shortInfoMutableAttributedString.append("\(name)\n".customAttributedString(font: Font.header, textColor: UIColor.darkGray))
}
if let age = detailsData.age {
shortInfoMutableAttributedString.append("\(age)\n".customAttributedString(font: Font.header, textColor: UIColor.darkGray))
}
shortInfoTextView.attributedText = shortInfoMutableAttributedString
}
fileprivate func fillCatInfo(detailsData: Car) {
contactButtonOutlet.isHidden = true
if let name = detailsData.name {
shortInfoMutableAttributedString.append("\(name)\n".customAttributedString(font: Font.header, textColor: UIColor.darkGray))
}
if let gender = detailsData.gender {
shortInfoMutableAttributedString.append("\(gender)\n".customAttributedString(font: Font.header, textColor: UIColor.darkGray))
}
shortInfoTextView.attributedText = shortInfoMutableAttributedString
}
还有其他方法可以用更少的代码填充此数据吗?
答案 0 :(得分:0)
经典的多态性案例,您应该创建一个协议并让Dog和Cat类实现它。然后,您可以仅在此协议实例上调用函数。
下面是一个简化的示例。在此示例中,进行区分是没有意义的,因为就属性而言,Cat
和Dog
都是同一类。如果您想区别一下,这将变得很有趣,例如,仅将bark()
类添加一个Dog
函数
protocol Pet{
var name: String { get set}
func infoString() -> String
}
class Dog: Pet{
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func infoString() -> String {
return "Dog \(name) has age \(age)"
}
}
class Cat: Pet{
var name: String
var gender: String
init(name: String, gender: String) {
self.name = name
self.gender = gender
}
func infoString() -> String {
return "Cat \(name) has gender \(gender)"
}
}
fileprivate func fillPetInfo(pet: Pet){
textView.text = pet.infoString()
}
let dog = Dog(name: "Ruffer", age: 8)
fillPetInfo(pet: dog)