Re: Substring in Swift
Re: Substring in Swift
- Subject: Re: Substring in Swift
- From: Quincey Morris <email@hidden>
- Date: Fri, 02 Sep 2016 10:23:49 -0700
- Feedback-id: 167118m:167118agrif8a:167118sxgINrHwvc:SMTPCORP
On Sep 2, 2016, at 06:32 , Gerriet M. Denkmann <email@hidden> wrote:
>
> The solution in Swift I have found uses NSString to cope with NSRange:
>
> // uitv is UITextView
> let swiftString = uitv.text
> let nsString = swiftString as NSString
> let selectedNSRange = uitv.selectedRange
> let selectedText = nsString.substringWithRange( selectedNSRange )
I believe this is the correct and only correct approach. I’ve seen people try to apply a NSRange to a Swift string’s UTF-16 “view", but I’m worried by the fact that UTF-16 representation is not unique, and there’s no guarantee that the original NSString and the UTF-16 view are in the same normal form, which would be the only way to avoid the problem.
My only quibble would be the double bridging:
> let swiftString = uitv.text // bridging from NSString to String
> let nsString = swiftString as NSString // bridging from String to NSString
Technically, bridging is a value conversion, though in practice the underlying concrete NSString subclass likely survives the “conversion". The danger is that there’s no API contract that prevents the generated code from *really* converting the underlying representation, and that might lead you back into the non-uniqueness-of-representation problem. So, I’d suggest:
> let nsString = uitv.text as NSString
which keeps you in the NSString domain.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden