简体   繁体   中英

Swift func that takes a Metatype?

As Apple says in the Metatype Type section in Swift's docs:

A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.

Is there a base class to refer to any class, struct, enum, or protocol (eg MetaType )?

My understanding is that protocol types are limited to use as a generic constraint, because of Self or associated type requirements (well, this is what an Xcode error was telling me).

So, with that in mind, maybe there is a Class base class for identifying class references? Or a Type base class for all constructable types (class, struct, enum)? Other possibilities could be Protocol , Struct , Enum , and Closure .

See this example if you don't get what I mean yet.

func funcWithType (type: Type) {
  // I could store this Type reference in an ivar,
  // as an associated type on a per-instance level.
  // (if this func was in a class, of course)
  self.instanceType = type
}

funcWithType(String.self)
funcWithType(CGRect.self)

While generics work great with 1-2 constant associated types, I wouldn't mind being able to treat associated types as instance variables.

Thanks for any advice!

This works:

func funcWithType (type: Any.Type) {
}

funcWithType(String.self)
funcWithType(CGRect.self)

Given your example an implementation would be:

// protocol that requires an initializer so you can later call init from the type
protocol Initializeable {
    init()
}

func funcWithType (type: Initializeable.Type) {
    // make a new instance of the type
    let instanceType = type()
    // in Swift 2 you have to explicitly call the initializer:
    let instanceType = type.init()

    // in addition you can call any static method or variable of the type (in this case nothing because Initializeable doesn't declare any)
}

// make String and CGRect conform to the protocol
extension String: Initializeable {}
extension CGRect: Initializeable {}

funcWithType(String.self)
funcWithType(CGRect.self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM