具有可初始化的Swift函数返回类型

时间:2017-08-29 10:37:33

标签: swift syntactic-sugar

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

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 个答案:

答案 0 :(得分:1)

您可以这样做:

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"