Have a variable with multiple types in Swift

An “enumeration with associated value” might be what you are looking for: enum StringOrInt { case string(String) case int(Int) } You can either assign a string or an integer: var value: StringOrInt value = .string(“Hello”) // … value = .int(123) Retrieving the contents is done with a switch-statement: switch value { case .string(let s): print(“String:”, … Read more

Self in init params

Instead of using Self or A in each of the initialisers, you can simply override each subclass’ initialiser to use its own type as operation. This works because A‘s initialiser states that operation should be a type that conforms to A, and when you override it you have the liberty to use a subclass of … Read more

TypeOf without an instance and passing result to a func

Yes, it’s possible. The trick is to start from a pointer to the type (whose value can be a typed nil, that’s perfectly OK), and then use Type.Elem() to get the reflect.Type descriptor of the pointed type (the base type). See some examples: t := reflect.TypeOf((*int)(nil)).Elem() fmt.Println(t) t = reflect.TypeOf((*http.Request)(nil)).Elem() fmt.Println(t) t = reflect.TypeOf((*os.File)(nil)).Elem() fmt.Println(t) … Read more

Multiple parameter closure argument type not inferred

See this scala-debate thread for a discussion of what’s going on here. The problem is that Scala’s type inference happens per parameter list, not per parameter. As Josh Suereth notes in that thread, there’s a good reason for the current approach. If Scala had per-parameter type inference, the compiler couldn’t infer an upper bound across … Read more

Build c# Generic Type definition at runtime

MakeGenericType – i.e. Type passInType = … /// perhaps myAssembly.GetType( “ConsoleApplication2.Program+Person”) Type t = typeof(List<>).MakeGenericType(passInType); For a complete example: using System; using System.Collections.Generic; using System.Reflection; namespace ConsoleApplication2 { class Program { class Person {} static void Main(){ Assembly myAssembly = typeof(Program).Assembly; Type passInType = myAssembly.GetType( “ConsoleApplication2.Program+Person”); Type t = typeof(List<>).MakeGenericType(passInType); } } } As suggested … Read more

Template type deduction in C++ for Class vs Function?

In specific cases you could always do like std::make_pair: template<class T> make_foo(T val) { return foo<T>(val); } EDIT: I just found the following in “The C++ Programming Language, Third Edition”, page 335. Bjarne says: Note that class template arguments are never deduced. The reason is that the flexibility provided by several constructors for a class … Read more