I am trying to create an enum that will allow me to create literals that combine Int, Double and String types, as well as any Array of any combination of those, and any Dictionary mapping a String to any combination of those. And make it nestable.
First I have the enum itself, and then several examples. Everything complies cleanly except for dict4 and dict5. Is type inference not expected to work for recursive enums? Or is this a bug in the compiler? If not is there any way to do this in pure swift that will compile? I realize that it's sort of unswifty to have such unstructured, stringly typed data like this. But in a pinch sometimes it's useful. Copy and paste this into a Playground to see the error message. (Contextual type 'protocol <>' cannot be used with array literal and Contextual type 'protocol <>' cannot be used with dictionary literal) enum RecursiveAny: StringLiteralConvertible, ArrayLiteralConvertible, IntegerLiteralConvertible, BooleanLiteralConvertible, FloatLiteralConvertible, DictionaryLiteralConvertible { case any(Any) indirect case anyDict([String:Any]) indirect case anyArr([Any]) // string literal convertible init(stringLiteral value: String) { self = .any(value) } init(extendedGraphemeClusterLiteral value: String) { self = .any(value) } init(unicodeScalarLiteral value: String) { self = .any(value) } // array literal convertible init(arrayLiteral elements: Any...) { self = .anyArr(elements) } init(dictionaryLiteral elements: (String, Any)...) { var dict = [String:Any]() for (key, value) in elements { dict[key] = value } self = .anyDict(dict) } // integer literal convertible init(integerLiteral value: Int) { self = .any(value) } // boolean literal convertible init(booleanLiteral value: Bool) { self = .any(value) } // float literal convertible init(floatLiteral value: Double) { self = .any(value) } } let string: RecursiveAny = "asdf" let int: RecursiveAny = 3 let float: RecursiveAny = 5.6 let array: RecursiveAny = ["asdf", 3, 5.6] let dict: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6 ] let dict2: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6, "array": array ] let dict3: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6, "array": dict ] let dict4: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6, "array": ["asdf", 3, 5.6] ] let dict5: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6, "dict": [ "string": "asdf", "int": 3, "float": 5.6 ] ] let dict6: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6, "array": RecursiveAny.anyArr(["asdf", 3, 5.6]) ] let dict7: RecursiveAny = [ "string": "asdf", "int": 3, "float": 5.6, "dict": RecursiveAny.anyDict([ "string": "asdf", "int": 3, "float": 5.6 ]) ]
_______________________________________________ swift-users mailing list swift-users@swift.org https://lists.swift.org/mailman/listinfo/swift-users