在Swift中是否可以区分布尔和整数?
我有一个在Swift中是否可以区分布尔和整数?,swift,integer,boolean,Swift,Integer,Boolean,我有一个AnyObject类型,可以是String、Int或Bool类型。我需要区分它们 此代码尝试这样做,但它认为Bool是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 bo
AnyObject
类型,可以是String
、Int
或Bool
类型。我需要区分它们
此代码尝试这样做,但它认为Bool
是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
func检查类型(值:T)->字符串{
var statusText=“未找到”
如果值为Int{
statusText=“它是一个整数”
}否则,如果值为Bool{
statusText=“它是一个布尔值”
}如果值为String,则为else{
statusText=“它是一个字符串”
}
返回状态文本
}
AnyObject
不能隐式向下转换为Swift中的任何类型。对于这种情况,您可以使用泛型
通用代码使您能够编写灵活、可重用的函数和类型,这些函数和类型可以根据您定义的需求与任何类型一起工作
我的工作方式是使用镜像结构
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")
}
在这里使用Any,因为Int、String和Bool都是结构。
如果您只是尝试使用来区分不同的类,那么应该是有效的
if value is NSString {
print("type is NSString")
}
checkType(true)返回“it is a integer”,此处不需要泛型<代码>值只能是type
Any
。这不适用于任何对象,因为它可以强制转换为Int或Bool
if value is NSString {
print("type is NSString")
}