I know it is possible to pass class type to a function in swift:
func setGeneric<T>(type: T.Type){ } setGeneric(Int.self)
But how we can return type from function? Writing something like
func getGeneric<T>() -> T.Type { return Int.self }
gives compiler error "Int is not identical to T". So is it possible to return type from a swift function?
Edit
Some explanation. I have classes that are used for persistence (I'm using Realm) and I have classes that acts as wrappers around this classes. All wrappers inherits from RealmClassWrapper
which needs to know what Realm class it actually wraps. So lets say I have this realm model:
class RealmTodo: RLMObject { dynamic var title = "" }
and my wrappers supper class looks like this:
class RealmClassWrapper { private let backingModel: RLMObject //... func backingModelType<T>() -> T.Type{ fatalError("must be implemented") } }
and actual wrapper:
class Todo: RealmClassWrapper { //some other properties func backingModelType<T>() -> T.Type{ return RealmTodo.self } }
You write an optional tuple return type by placing a question mark after the tuple type's closing parenthesis, such as (Int, Int)? or (String, Int, Bool)? . An optional tuple type such as (Int, Int)? is different from a tuple that contains optional types such as (Int?, Int?) .
If you want to return your own value from a function, you need to do two things: Write an arrow then a data type before your function's opening brace, which tells Swift what kind of data will get sent back. Use the return keyword to send back your data.
Show activity on this post. Answer extracted from question: It seems the problem is, that swift does not exit the function instantly on a return statement in a void function and uses the consecutive void value as the function parameter and terminates as expected if it is non-void.
The Any type represents values of any type, including optional types. Swift gives you a warning if you use an optional value where a value of type Any is expected. If you really do need to use an optional value as an Any value, you can use the as operator to explicitly cast the optional to Any , as shown below.
You can return any type you want.
func getTypeOfInt() -> Int.Type { return Int.self } func getTypeOfBool() -> Bool.Type { return Bool.self }
If the type is not determined from arguments or if the return is constant, there is no need to introduce a generic T
type.
It works when I modify your function like this:
func getGeneric<T>(object: T) -> T.Type { return T.self } getGeneric(0) // Swift.Int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With