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

J.D. Healy jdhealy at gmail.com
Tue May 3 10:48:41 CDT 2016


Confused about getAsNSString from bullet point 5, used again in bullet
point 8 — the function wont compile for me:


> 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 = nilgetAsNSString(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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160503/9ca774b0/attachment.html>


More information about the swift-evolution mailing list