How to fix cast warning in "if let" expression in Xcode 8.3?

Consider the following code:

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

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

Dropped from NSData to Data . How to fix it?

+5
source share
3 answers

Try adding to optional data:

 if let date = nsdate as Date? 

You are trying to make the optional composition of the optional NSDate < optional date. So far, NSDate connecting to obj-c on Date , so this listing always succeeds, so the optional addition required here is as simple as casting. Then you need to specify an optional value, so the final value should be optional, so Date? fits here.

+17
source

Swift 3.1 features

  • Optional down listing as? Foo as? Foo

    It distinguishes more non-specific for a more specific type, for example

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

    These are the Foundation Type bridges for the free Swift type and vice versa.

    This is an optional equivalent to the usual 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, do not use NS... Foundation classes in Swift 3 if you have a native Swift instance.

+5
source

Try the following:

 let nsdate: NSDate? = NSDate() if let date = nsdate { print(date) } 

The compiler knows this is an NSDate if it is unpacked, so what you do actually throws the NSDate to Date

0
source

Source: https://habr.com/ru/post/1266689/


All Articles