如何匹配Swift中对象的数据类型?
喜欢:
var xyz : Any
xyz = 1;
switch xyz
{
case let x where xyz as?AnyObject[]:
println("\(x) is AnyObject Type")
case let x where xyz as?String[]:
println("\(x) is String Type")
case let x where xyz as?Int[]:
println("\(x) is Int Type")
case let x where xyz as?Double[]:
println("\(x) is Double Type")
case let x where xyz as?Float[]:
println("\(x) is Float Type")
default:println("None")
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,开关盒运行默认情况
Objective-C有两种方法来测试对象是否是特定类或子类的实例:
- (BOOL)isMemberOfClass:(Class)aClass;
Run Code Online (Sandbox Code Playgroud)
返回一个布尔值,指示接收者是否是给定类的实例.
- (BOOL)isKindOfClass:(Class)aClass;
Run Code Online (Sandbox Code Playgroud)
返回一个布尔值,指示接收者是给定类的实例还是从该类继承的任何类的实例.
在Swift中,我可以使用is运算符测试后者:
if myVariable is UIView {
println( "I'm a UIView!")
}
if myVariable is MyClass {
println( "I'm a MyClass" )
}
Run Code Online (Sandbox Code Playgroud)
如何测试实例是否是Swift中的特定类或类型(即使在处理没有NSObject子类时)?
注意:我知道func object_getClassName(obj: AnyObject!) -> UnsafePointer<Int8>.
我有一个JSON
{
"tvShow": {
"id": 5348,
"name": "Supernatural",
"permalink": "supernatural",
"url": "http://www.episodate.com/tv-show/supernatural",
"description": "Supernatural is an American fantasy horror television series created by Eric Kripke. It was first broadcast on September 13, 2005, on The WB and subsequently became part of successor The CW's lineup. Starring Jared Padalecki as Sam Winchester and Jensen Ackles as Dean Winchester, the series follows the two brothers as they hunt demons, ghosts, monsters, and other supernatural beings in the world. The series is produced …Run Code Online (Sandbox Code Playgroud) 现在我需要一种方便的方法来获取枚举本身的名称?这是一个例子.
enum SimpleEnum {
case firstCase
case secondCase
case thirdCase
}
let simpleEnum: SimpleEnum = .firstCase
print("\(simpleEnum)") // return the "firstCase", but I want "SimpleEnum"
Run Code Online (Sandbox Code Playgroud)
我知道以下代码可行.
enum SimpleEnum: CustomStringConvertible {
case firstCase
case secondCase
case thirdCase
var description: String { return "SimpleEnum" }
}
let simpleEnum: SimpleEnum = .firstCase
print("\(simpleEnum)") // Ok, it return "SimpleEnum"
Run Code Online (Sandbox Code Playgroud)
但是,我只想要一种通用方式,而不是为每个枚举键入"SimpleEnum".
代码如下,在OC中使用[touch.view类]获取对象类型,在Swift 3中如何获取它.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
return NO;
} else {
return YES;
}
}
Run Code Online (Sandbox Code Playgroud)