在swift中将类名作为参数发送
如何在swift中将类名作为参数发送?以下是我努力实现的目标:在swift中将类名作为参数发送,swift,object,protocols,Swift,Object,Protocols,如何在swift中将类名作为参数发送?以下是我努力实现的目标: 我有一个对象,我希望它将两个不同的对象(对象A,对象B)作为其初始值设定项的一部分 此外,我还需要确保两个对象都包含一个UIImageView来查看它们中的每一个 例如: class A { var view: UIImageView! //rest of the code for object A } class B { var imageView: UIImageView! //rest of
class A {
var view: UIImageView!
//rest of the code for object A
}
class B {
var imageView: UIImageView!
//rest of the code for object B
}
class C {
init(someClass1: AnyClass, someClass2: AnyClass) {
//make sure someClass1.imageView
//make sure someClass2.imageView
}
//rest of the code for object C
}
所以,基本上我需要发送这些类名/类型来初始化C类,并且A和B符合并具有UIImageView。我想它应该是类似于协议的东西,但不确定如何在这里实现它
谢谢 有两种方法:协议或继承。协议通常是可行的,因为它们更灵活。Objective C中有一个庞大的协议传统,因为该语言不支持多重继承,但Swift支持!选择协议或继承的原因不是基于Swift中的语言,而是纯粹基于体系结构,这很好。因此,根据应用程序的结构,您应该选择最佳方法 使用协议:
// Any class conforming to the protocol P must
// have a property called view because it is not optional
protocol P {
var view: NSImageView? { get set }
}
class A: P {
var view: NSImageView?
// ...
}
class B: P {
var view: NSImageView?
// ...
}
class C {
init(someClass1: P, someClass2: P) {
if someClass1.view != nil && someClass2.view != nil {
// ...
}
}
}
使用继承:
// Parent class. Any subclass already includes all the
// properties and methods, so you don't have to redeclare them.
class P {
var view: NSImageView?
}
class A: P {
}
class B: P {
}
class C {
init(someClass1: P, someClass2: P) {
if someClass1.view != nil && someClass2.view != nil {
// ...
}
}
}
谢谢在根据你的答案做了一些研究之后,我想补充一下。。。如果需要协议一致性(A为?P,A为P),则协议P应为objc协议(@objc协议P…)