2017-03-19 5 views
0

私はこの機能を実現するために必要なパラメータとして、クラス型をパスし、そのインスタンスを作成します。その後

  • はパラメータとしてクラス型を渡しを
  • チェッククラス型
  • 私が呼び出す必要がある場合インスタンスメソッド、それをインスタンス化し、
  • 関数を呼び出すまたは静的クラスメソッドに

クラス

を呼び出します
class Foo{ 
    func method1() 
} 

class Bar{ 
    static method2() 
} 

そして、受信方法で:

func receiveClassType(type:AnyClass){ 

    //check class type 
    //If class Foo, cast received object to Foo, instantiate it and call method1() 
    //If class Bar, cast received class to Bar call static method method2() 

} 

感謝します。

答えて

1

にはがクラスタイプからインスタンス化されていますか?これは、Objective-Cランタイムの動的機能のおかげで、Objective Cで機能します。あなたがスウィフトで達成できるものではありません。

たぶん...列挙型を使用することを検討して

enum Classes: String { 
    case foo, bar 

    func instantiate() -> Any { 
     var result: Any 
     switch self { 
     case .foo: 
      let foo = Foo() 
      foo.method1() 
      result = foo 
     case .bar: 
      let bar = Bar() 
      bar.method2() 
      result = bar 
     } 
     return result 
    } 
} 

func receiveClassType(type: String){ 

    guard let aClass = Classes(rawValue: type) else { return } 

    aClass.instantiate() 

}