有Swift函数return类型可以初始化

Have Swift function return type that can be initialized

我想要一个函数 return 可以初始化的类型(可能以特定方式,例如使用特定参数)。可以通过许多其他方式获得相同的结果,但我特别在寻找这种语法糖。 我想知道是否可以用类似这样的方式来完成:

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")()

你可以这样做:

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"