[swift-evolution] [Pitch] Reducing the bridging magic in dynamic casts

Joe Groff jgroff at apple.com
Tue May 3 10:49:46 CDT 2016


> On May 3, 2016, at 8:48 AM, J.D. Healy <jdhealy at gmail.com> wrote:
> 
> Confused about getAsNSString from bullet point 5, used again in bullet point 8 — the function wont compile for me:

There's a typo. getAsNSString needs to return an optional, `NSString?`, because the cast produces nil if it fails.

-Joe

>  
> Check whether a value is _ObjectiveCBridgeable to a class, or conversely, that an object is _ObjectiveCBridgeable to a value type, and perform the bridging conversion if so:
> func getAsString
> <T>(value: T) -> String? {
>   
> return value as
> ? String
> }
> 
> func getAsNSString
> <T>(value: T) -> NSString {
>   
> return value as
> ? NSString
> }
> 
> getAsString(value: 
> "string") // produces "string": String
> 
> getAsNSString(value: 
> "string") // produces "string": NSString
> 
> 
> 
> let ns = NSString("nsstring"
> )
> getAsString(value: ns) 
> // produces "nsstring": String
> 
> getAsNSString(value: ns) 
> // produces "nsstring": NSString
> 
> Drill through Optionals. If an Optional contains some value, it is extracted, and the cast is attempted on the contained value; the cast fails if the source value is none and the result type is not optional:
> 
> var x: String? = "optional string"
> 
> getAsNSString(
> value: x) // produces "optional string": NSString
> 
> x = nil
> 
> getAsNSString(value: x) // fails
> $ /Applications/Xcode-7D1010.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift
> Welcome to Apple Swift version 2.2 (swiftlang-703.0.18.5 clang-703.0.31). Type :help for assistance.
>   1> import Foundation
>   2>
>   3> func getAsNSString<T>(value: T) -> NSString {
>   4.   return value as? NSString
>   5. }
> repl.swift:4:16: error: value of optional type 'NSString?' not unwrapped; did you mean to use '!' or '?'?
>   return value as? NSString
>                ^
>          (                 )!
> 
>   3>
> 
> $ /Library/Developer/Toolchains/swift-DEVELOPMENT-SNAPSHOT-2016-04-12-a.xctoolchain/usr/bin/swift
> Welcome to Apple Swift version 3.0-dev (LLVM 752e1430fc, Clang 3987718dae, Swift 36739f7b57). Type :help for assistance.
>   1> import Foundation
>   2>
>   3> func getAsNSString<T>(value: T) -> NSString {
>   4.   return value as? NSString
>   5. }
> error: repl.swift:4:16: error: value of optional type 'NSString?' not unwrapped; did you mean to use '!' or '?'?
>   return value as? NSString
>                ^
>          (                 )!
> 
> I would think the function was meant to end -> NSString?, if not for the // fails comment in bullet 8. Could you clarify?
> 
> – J.D. Healy
> 



More information about the swift-evolution mailing list