Bool Bool - 4 months ago 13
Swift Question

parameters without type annotation swift

I have a function that checks the type of arguments it takes in but it seems difficult for me to define a parameter that can work with any type annotation. Here's my been-trying:

//bool
var x = 0, y = 3.142, z = "hello"
func checkType(input: /*here's my problem*/) -> String {
let res = "That is of type \(input.dynamicType)"
return res
}
print(checkType(//argument))
//

Answer

You answered yourself

[...] that can work with any type [...]

Here's the code

func checkType(input: Any) -> String {
    let res = "That is of type \(input.dynamicType)"
    return  res
}

Test

checkType("Hello") // "That is of type String"
checkType(true) // "That is of type Bool"
checkType(123) // "That is of type Int"
Comments