小编kar*_*ski的帖子

Swift"is"运算符,其类型存储在变量中

这段代码按预期工作.输出中打印"integer is int".

let integer = Int()

if integer is Int {
    println("integer is int")
}
else {
    println("integer is not int")
}
Run Code Online (Sandbox Code Playgroud)

我想以is与使用isKindOfClass方法相同的方式使用运算符- 将类(或更确切地说类型)存储在变量中.它看起来像这样:

let integer = Int()
let intType : Any = Int.self

if integer is intType {
    println("Integer is int")
}
else {
    println("Integer is not int")
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会产生错误:Use of undeclared type 'IntType'.

IntTypeif条件甚至具有不同的颜色(如果您将其粘贴到操场)比在源代码中的其他地方,这表明(如错误消息指出)其被视为一个类名(如IntType将是一个类).但事实并非如此.这意味着is运算符不能与右侧的变量一起使用?

我想使用is运算符,因为它不仅可以比较类,还可以比较其他类型.

如何检查值是否具有我期望的类型?


我找到了肮脏的解决方案,但它真的远非可靠......

let integer = Int()
let …
Run Code Online (Sandbox Code Playgroud)

types swift

11
推荐指数
1
解决办法
5064
查看次数

在Swift中创建运行时已知的类实例

一张图片胜过千言万语,如何将这段代码从Objective-C重写为Swift?

- (id) instanceOfClass: (Class) class withInitializer: (SEL) initializerSelector withObject: (id) object {
    id obj = nil;
    if([class instancesRespondToSelector:initializerSelector]) {
        obj = [[class alloc] performSelector:initializerSelector
                                  withObject:object];
    }
    return obj;
}

id myViewController = [self instanceOfClass:[ViewController class]
                              withInitializer:@selector(initWithObject:)
                                   withObject:@"super-string!"];
NSLog(@"%@", myViewController);
Run Code Online (Sandbox Code Playgroud)

dynamic instantiation swift

10
推荐指数
1
解决办法
6973
查看次数

标签 统计

swift ×2

dynamic ×1

instantiation ×1

types ×1