How to declare a function argument that can accept any type in Swift

1 Answer

0 votes
import Foundation

func acceptAnyType(_ x: Any) {
    switch x {
    case let v as Int:
        print("int: \(v)")
    case let v as Double:
        print("float: \(v)")
    case let v as String:
        print("string: \(v)")
    case let v as Bool:
        print("bool: \(v)")
    case let v as Character:
        print("char: \(v)")
    default:
        print("unknown type")
    }
}

acceptAnyType(9821)
acceptAnyType(3.14)
acceptAnyType("ABCD")
acceptAnyType(true)
acceptAnyType(Character("A"))



/*
run:

int: 9821
float: 3.14
string: ABCD
bool: true
char: A

*/

 



answered Aug 1, 2025 by avibootz
...