如何让我的函数在swift中接受两个不同的对象?

coo*_*lly 7 oop function ios swift

我有一个函数,它需要一个参数.我希望我的函数接受两种对象类型.我该怎么做?以下是以下示例:

func accept(user: Customer) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

它应该接受Customer和Employee对象引用.

accept(objRefCustomer)
accept(objRefEmployee)
Run Code Online (Sandbox Code Playgroud)

在这种情况下请帮帮我.

dfr*_*fri 6

替代超类:使用协议

在这种情况下,您不一定需要使用超类(如果CustomerEmployee是结构值类型;超类选项是不可能的),而是可以使用更通用的协议方法。

定义一个协议Users,为您的CustomerEmployee实例的属性和方法绘制蓝图(如果我们让Customer并且Employee符合Users,那么我们保证这两个结构的实例将可以访问蓝图的属性和方法):

protocol Users {
    var name: String { get }
    func printTypeOfUser()
}
Run Code Online (Sandbox Code Playgroud)

定义CustomerEmployee结构,以及它们对协议的一致性Users

struct Customer : Users {
    let name: String
    init(name: String) { self.name = name }

    func printTypeOfUser() {
        print("Is a Customer!")
    }
}

struct Employee : Users {
    let name: String
    let id: Int
    init(name: String, id: Int) { self.name = name; self.id = id }
    
    func printTypeOfUser() {
        print("Is an Employee!")
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以定义一个泛型函数,它的泛型,比如说T,被类型约束为符合协议的类型Users,在这种情况下,它等价于CustomerorEmployee类型

func accept<T: Users>(user: T) {
    print("Name of user: \(user.name) [\(user.dynamicType)]")
    user.printTypeOfUser()
    
    // do something additional employee-specific if user is an employee?
    if let employee = user as? Employee {
        print("User is an employee with id: \(employee.id)")
    }
}
Run Code Online (Sandbox Code Playgroud)

此函数的示例用法Employee以及Customer实例:

let employee = Employee(name: "John", id: 1)
let customer = Customer(name: "Sarah")

accept(employee) /* Name of user: John [Employee] 
                    Is an Employee!
                    User is an employee with id: 1 */

accept(customer) /* Name of user: Sarah [Customer]
                    Is a Customer!                 */
Run Code Online (Sandbox Code Playgroud)


NSN*_*oob 5

您可以使用代替更改类结构和代码库AnyObject。例如,如果将来将来您必须使此函数接受class的参数,这对您也将变得更加容易WaterMelon。使所有这些类都从公共父类继承将是不必要的开销,更不用说忙碌了。

AnyObject快速等同于目标c id。AnyObject是可以代表任何类类型的实例的协议。

它还有一个更通用的对应物,Any它可以代表任何类型(包括structsenums)。

以下代码将接受您传递的任何类类型参数:

func accept(sender : AnyObject) { //Or AnyObject? if you want to handle nil as well
      ...
    }
Run Code Online (Sandbox Code Playgroud)

要访问传递为的类的属性AnyObject,可以使用类型转换

例如下面的代码将检查发件人类型并为您键入类型:

if let customerRef = sender as? Customer {
    // ...
    // Sender is of customer class type. Use it with customerRef that we created
    let customerName = customerRef.dynamicType.sampleNameProperty //Access a property of class Customer
    customerRef.funcOfCustomerClass() //Call a method of class Customer
}
else{
 //Sender is not of customer class type. 
//Then it must be Employee??? Handle cases for employee here.
}
Run Code Online (Sandbox Code Playgroud)