代码之家  ›  专栏  ›  技术社区  ›  Kamran

从字符串创建类类型以作为具体类型传递给泛型参数swift

  •  3
  • Kamran  · 技术社区  · 6 年前

    protocol P ,请 class A and B a<T: P>(_: T.Type)

    protocol P: class {
        static var p: String { get }
    }
    
    extension P {
        static var p: String { return String(describing: self) }
    }
    
    class A: P {
    
        func a<T: P>(_: T.Type) {
            print(T.p)
        }
    }
    
    class B: P {}
    

    下面的代码之所以有效,是因为强制强制转换为B。类型修复了类类型

    let b = "B"
    let type = NSClassFromString(b) as! B.Type
    A().a(type)
    

    ["ClassA", "ClassB", "ClassC"].forEach({ className in
       let type = NSClassFromString(className) as! ????
       A().a(type)
    })
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   OOPer    6 年前

    ???? 需要是符合 P A.Type B.Type

    P.Type 不符合 以迅捷的速度前进。


    a(_:)

    class A: P {
    
        func a(_ type: P.Type) {
            print(type.p)
        }
    
    }
    
    ["ModuleName.A", "ModuleName.B"].forEach({ className in
        let type = NSClassFromString(className) as! P.Type
            A().a(type)
    })