1

Objective-C では、関数は、パブリック クラスとパブリック プロトコルを実装するプライベート型のインスタンスを、そのプロトコルに準拠するパブリック クラスを定義しなくても返すことができます。

たとえば、次のヘッダー ファイルがあるとします。

@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他の型)について実際には決して知りませんが、返されるオブジェクトが と の両方を実行できることを確認できます。AnimalFlyerrandomFlyingAnimaleatfly

そのようなことはSwiftで可能ですか?

4

1 に答える 1

0

Swift で適用できるいくつかのアプローチがありますが、おそらくプロトコルAnimalTypeとプロトコルを定義することになるでしょうFlyerType。これらは互いに関係がありません。

public protocol AnimalType {}
public protocol FlyerType {
    func fly()
}

次に、次のように内部クラスまたはプライベート クラスを作成します。

internal class Animal: AnimalType {}
internal class Bird: Animal {}
internal class Bat: Animal {}

現在、 classBirdおよびは、その基本クラスから継承することでBat準拠しています。同様に準拠するために、 これらのクラスを次のように拡張できます。AnimalTypeAnimalFlyerType

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>プロトコル構成タイプです。この場合、そのアプリケーションが役立つと思われます。

于 2016-02-04T09:33:02.057 に答える