Swift:我可以返回一个实现公共类并符合公共协议的私有类型吗?

时间:2016-02-04 07:27:32

标签: swift inheritance swift-protocols

在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返回的对象可以eatfly

在Swift中这样的事情可能吗?

1 个答案:

答案 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,类BatAnimalType符合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 - 在这种情况下,其应用似乎很有用。