78051

Is it possible to distinguish Bool and Int in Swift?

Question:

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

Answer1:

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.

<blockquote>

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. <a href="https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html" rel="nofollow">Read more</a>.

</blockquote>

Answer2:

The way worked with me is by using the <strong>Mirror</strong> struct.

let value: Any? = 867 let stringMirror = Mirror(reflecting: value!) let type = stringMirror.subjectType print(stringMirror.subjectType) if type == Bool.self { print("type is Bool") } else if type == String.self { print("type is string") } else if type == Int.self { print("type is Int") }

use <strong>Any</strong> here since <em>Int, String, Bool</em> are structs. if you just try to distinguish between classes using <strong>is</strong> should work.

if value is NSString { print("type is NSString") }

Recommend