Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the warning of type casting in 'if let' statement in Xcode 8.3?

Tags:

swift

swift3

Consider the following code:

let nsdate: NSDate? = NSDate()
if let date = nsdate as? Date { // a warning occurs here
    print(date)
}

The compiler complains like this: Conditional downcast from 'NSDate?' to 'Date' is a bridging conversion; did you mean to use 'as'?

A cast from NSData to Data has the same problem. How to fix the it?

like image 619
Vitreous-Flower Avatar asked Apr 13 '17 12:04

Vitreous-Flower


2 Answers

Try to cast to an optional Date:

if let date = nsdate as Date?

You're trying to optional cast of optional NSDate to NON optional Date. As long as NSDate is bridged from obj-c to Date, so this cast always success, so no optional cast required here, just basic cast as is enough. Then you need to cast optional value, so the resulting value has to be optional too, therefore Date? is appropriate here.

like image 55
Jurasic Avatar answered Nov 05 '22 17:11

Jurasic


Swift 3.1 distinguishes

  • An optional down cast as? Foo

    It casts a more unspecific to a more specific type for example

    let dict : [String:Any] = ["Foo" : 12]
    let number = dict["Foo"] as? Int
    
  • A bridge cast of an optional type as Foo?

    It bridges a (Core)Foundation type to a toll free Swift type and vice versa.

    It's the optional equivalent of the usual non-optional syntax

    let string : NSString = "Foo"
    let swiftString = string as String
    

The difference is subtle for the developer but very useful for the compiler.

Basically don't use the NS... Foundation classes in Swift 3 if there is a native Swift counterpart.

like image 41
vadian Avatar answered Nov 05 '22 18:11

vadian