Peter Shaw Peter Shaw - 5 months ago 8
Swift Question

Is it possible to distinguish Bool and Int in Swift?

I have an

AnyObject
type that can be
String
,
Int
or
Bool
type. I need to distinguish them.

This code tries to do so, but it considers
Bool
to be
Int
:

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

Answer
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.

Comments