在Objective-C中,函数能够返回实现公共类和公共协议的私有类型的实例,而无需定义符合该协议的公共类。
E.g。我们说我有这个头文件:
@protocol Flyer <NSObject>
-(void) fly;
@end
@interface Animal : NSObject
-(void) eat;
@end
Animal<Flyer> * randomFlyingAnimal();
这个实现文件:
@implementation Animal
-(void) eat {
NSLog(@"I'm eating");
}
@end
@interface Bird : Animal<Flyer>
@end
@implementation Bird
-(void) fly {
NSLog(@"I'm a flying bird");
}
@end
@interface Bat : Animal<Flyer>
@end
@implementation Bat
-(void) fly {
NSLog(@"I'm a flying bat");
}
@end
Animal<Flyer> * randomFlyingAnimal() {
switch (arc4random() % 2) {
case 0:
return [[Bird alloc] init];
case 1:
default:
return [[Bat alloc] init];
}
}
在此示例中,我的代码的使用者实际上从未真正了解Bird
类或Bat
类(或实现Animal
的任何其他类型并且符合Flyer
),但可以确保从randomFlyingAnimal
返回的对象可以eat
和fly
。
在Swift中这样的事情可能吗?
答案 0 :(得分:0)
您可以在Swift中应用一些方法,但您可能会定义协议AnimalType
和协议FlyerType
- 它们之间没有关系:
public protocol AnimalType {}
public protocol FlyerType {
func fly()
}
然后,按如下方式创建内部或私有类:
internal class Animal: AnimalType {}
internal class Bird: Animal {}
internal class Bat: Animal {}
现在,通过继承基类Bird
,类Bat
和AnimalType
符合Animal
。为了符合FlyerType
,我们可以扩展这些类,如下所示:
extension Bird: FlyerType {
internal func fly() { print("Bird's flying") }
}
extension Bat: FlyerType {
internal func fly() { print("Bat's flying") }
}
您的工厂功能可以如下实现:
public func randomFlyingAnimal() -> protocol<AnimalType, FlyerType> {
switch (arc4random() % 2) {
case 0: return Bird()
default: return Bat()
}
}
protocol<AnimalType, FlyerType>
是protocol composition type - 在这种情况下,其应用似乎很有用。