2014-09-01 287 views
1

类型检查,我不能这样做,我认为应该工作以下类型检查:斯威夫特

var str:String? 

//Compiler error: Downcast from 'String?' to 'String' only unwraps optional; did you mean to use '!'? 
if str is String { 

} 

//Compiler error: is test is always true 
if str! is String { 
    println("str is optional string") 
} 
+0

我想说明使用is型检查。 – Boon 2014-09-01 20:21:25

回答

6

"Type-Casting Operators"在斯威夫特文档 (重点煤矿):

的是运算符会在运行时检查该表达式是否可以向下转换为指定的类型 。如果表达式可以将 向下转换为指定的类型,则返回true;否则,它返回false。 如果转换为指定类型保证成功或失败,则会引发编译时错误。

String不是String?String适当的子类,因此is 操作者不能在此处使用。要检查str是否有值,可以使用 可选分配:if let theString = str { ... }

工作的例子:

class A { } 
class B : A { } 

func foo(a : A) { 
    if a is B { 
     // a is an instance of the B subclass 
    } 
} 

func bar(obj: AnyObject) { 
    if obj is NSNull { 
     // The Null object 
    } 
} 

在许多情况下,有条件的投as?是因为它返回更多有用的 指定类型的值:

func foo(a : A) { 
    if let b = a as? B { 
     // ... 
    } 
} 
+0

使用“is”检查的关键是它是否可以降级。如果字符串不能转换为字符串?,那么它应该返回false,否?否则,我们如何检查类型? – Boon 2014-09-01 22:36:24

+0

@Boon:字符串不能被转换为字符串?将字符串投射到字符串?是*保证失败*,因此编译器错误(如上面引用的文档中所述)。 - 对于'var str:AnyObject?',你可以测试'如果str是String ...'。 – 2014-09-02 07:49:14

0

strString?这是可选; 可选不能是String,因为它是完全不同的类型。因此if str is String可以从来没有是真实的,编译器告诉你有关它。

str!同样解开Sting?,其结果是总是String。因此if str! is String总是如此。

采用is示出为具有:

class Shape {} 
class Rectangle : Shape {} 
class Circle : Shape {} 

func draw (s:Shape) { 
    if s is Rectangle {} 
    else if s is Circle {} 
    else {} 
} 

draw函数,编译器识别出RectangleCircle是的参数Shape类型并且因此if语句允许亚型。