在Swift中可以区分Bool和Int吗? [英] Is it possible to distinguish Bool and Int in Swift?
本文介绍了在Swift中可以区分Bool和Int吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个AnyObject
类型,可以是String
,Int
或Bool
类型.我需要区分它们.
I have an AnyObject
type that can be String
, Int
or Bool
type. I need to distinguish them.
此代码试图这样做,但是它认为Bool
是Int
:
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
推荐答案
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
不能隐式向下转换为Swift中的任何类型.在这种情况下,您可以改用Generics
.
AnyObject
cannot be implicitly downcast to any type in Swift. For such case you can use Generics
instead.
使用通用代码,可以根据您定义的要求编写灵活的,可重用的函数和类型,这些函数和类型可以与任何类型一起使用. 了解更多.
这篇关于在Swift中可以区分Bool和Int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文