Peter Shaw Peter Shaw - 3 months ago 5x
Swift Question

Is it possible to distinguish Bool and Int in Swift?

I have an

type that can be
type. I need to distinguish them.

This code tries to do so, but it considers
to be

import Cocoa

var value: AnyObject

func checkType(value: AnyObject) -> String {
if let intvalue: Int = value as? Int {
return("It is an integer")
} else if let boolvalue: Bool = value as? Bool {
return("It is an boolean")
} else if let stringvalue: String = value as? String {
return("It is an string")
return "not found"

value = "hello"
checkType(value) // It is an string

value = 1
checkType(value) // It is an integer

value = true
checkType(value) // It is an integer

func checkType<T>(value: T) -> String {
    var statusText = "not found"
    if value is Int {
        statusText = "It is an integer"
    } else if value is Bool {
        statusText = "It is an boolean"
    } else if value is String {
        statusText = "It is an string"
    return statusText

AnyObject cannot be implicitly downcast to any type in Swift. For such case you can use Generics instead.

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. Read more.