ios - 作用于所有类的通用方法

标签 ios swift

我有类

class Citizen{

    var name:String
    var age:Int
    var lawPrevilige = 0

    init(name:String,age:Int){

        self.name = name
        self.age = age
    }
}

class Politician{

    var name:String
    var age:Int
    var lawPrevilige = 1

    init(name:String,age:Int){

        self.name = name
        self.age = age
    }

}

还有一个类来操纵这些

class PoliceDept{

    var departMentName = "InterPol"
    var departMentAddress:String = "Earth"

    //this method should be able to access object of any class with the same properties.
    func investigateAnyOne(person:AnyObject){


        if let p = person as? Citizen{

            print(p.name)


        }else if let po =  person as? Politician{

            print(po.name)
        }
    }
}

现在的问题是,如果我有一个类 Disabled PeopleUnderAge People 等具有确切的属性名称和年龄..那么我如何制作方法 警察部门的 investigateAnyOne 在没有类型转换的情况下对 AnyObject 进行操作。这可能吗?

向下转换为 10-12 个类的每种类型的对象会使代码变得困惑。我是否应该创建多个 if else 语句来检查类的类型或任何其他符合协议(protocol)的方式。

问题是如果有许多其他类型的人我想调查,我该怎么办..

最佳答案

创建一个Protocol 并在其中定义所有属性,并在所有类中遵循Common Protocol。因此您无需在 investigateAnyOne 中检查多个案例。

protocol Common {
var name:String {get set}
var age:Int {get set}
 var lawPrevilige:Int {get set}

}

class Politician: Common{

 var name:String
 var age:Int
 var lawPrevilige = 1

 init(name:String,age:Int){

 self.name = name
 self.age = age
 }

}

class PoliceDept{

 var departMentName = "InterPol"
 var departMentAddress:String = "Earth"


 func investigateAnyOne(person: Common){
   self.departMentName = person.name
  }
}

创建一个 Politician 对象并将其传递给 investigateAnyOne 方法。

let politician = Politician(name: "demo", age: 10)
let policeDept = PoliceDept()
 policeDept.investigateAnyOne(politician)

关于ios - 作用于所有类的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40588209/

相关文章:

ios - 检查是否使用 QuickAction 打开了 ViewController

ios - 单击删除按钮,Swift,删除/删除页面 View Controller 内显示的 Controller

ios - 为什么UICollectionViewCell的outlet在Interface Builder Xcode7.1 OS X Yosemite中为nil?

ios - Swift 中的日期到毫秒并返回到日期

ios - 应用程序因 Info.plist 文件麦克风中缺少用途字符串而被拒绝,但我无法在 info.plist 中添加描述

ios - 如何在 Swift 中以编程方式从另一个图像中剪切 Logo (png 图像)的形状?

swift - 跟踪 NSCell 的位置变化

ios - 您如何直接链接到 iOS 上的应用评论部分

ios - UITableView 单元格文本标签不显示文本

iOS IDFA : Firebase and Google Adwords Universal App Campaign Setup