Have Swift function return type that can be initialized

102 views Asked by At

I would like a function to return a type that can be initialized (potentially in a specific way e.g. with specific arguments). Getting the same result is possible in many other ways, but I'm specifically looking for this kind of syntactic sugar. I wonder if it could be done in a way similar to this:

protocol P {
    init()
}

extension Int: P {
    public init() {
        self.init()
    }
}

// same extension for String and Double

func Object<T: P>(forType type: String) -> T.Type? {

    switch type {

    case "string":
        return String.self as? T.Type


    case "int":
        return Int.self as? T.Type

    case "double":
        return Double.self as? T.Type

    default:
        return nil
    }
}

let typedValue = Object(forType: "int")()
1

There are 1 answers

0
sCha On BEST ANSWER

You can do something like this:

protocol Initializable {
    init()
}

extension Int: Initializable { }

extension String: Initializable { }

func object(type: String) -> Initializable.Type? {
    switch type {
    case "int":
        return Int.self
    case "string":
        return String.self
    default:
        break
    }
    return nil
}

let a = object(type: "string")!.init()
print(a)  // "\n"