Re: Swift: How to determine if a Character represents whitespace?
Re: Swift: How to determine if a Character represents whitespace?
- Subject: Re: Swift: How to determine if a Character represents whitespace?
- From: Quincey Morris <email@hidden>
- Date: Thu, 02 Apr 2015 18:15:07 +0000
On Apr 2, 2015, at 04:54 , Charles Jenkins <email@hidden> wrote:
> Swift has a built-in func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String
There is something wacky going on here — or not. (I know you don’t want to use this particular method, but I’m just using it as an example.)
First of all, String and NSString are different classes, for real. Quoting a god-like personage, in a recent thread:
> On Mar 23, 2015, at 13:52 , Greg Parker <email@hidden> wrote:
>
>> Most of NSString's methods are re-implemented in a Swift extension on class String. You get this extension when you `import Cocoa`.
And indeed, if you try this in a playground:
> let strA = "Hello, string"
> let strB = "Hello, NSString" as NSString
> let a = strA.characterAtIndex (6) // line 3
> let b = strB.characterAtIndex (6) // line 4
you get an error at line 3, as you would expect/hope (since Strings aren’t “made of” unichars), but no error in line 4 (since NSStrings are).
So it’s not odd that String.stringByTrimmingCharactersInSet would return a String. What’s very odd is that *in Swift* NSString.stringByTrimmingCharactersInSet returns a String — not a NSString — as does NSAttributedString.string, or apparently any Cocoa API that would return a NSString in Obj-C.
This means it’s not possible *in Swift* to apply NSString methods to a NSString and stay entirely within the NSString world without casting/converting. *That’s* wacky, given that String and NSString are different classes with different (though very similar) APIs.
The only way to un-wack this, that I can think of right now, would be for expressions like ‘someNSString.stringByTrimmingCharactersInSet (…) as NSString’ to involve only a cheap or free conversion from String to NSString. However there is no API contract to this effect AFAIK.
Therefore:
1. We need a god-like personage to step in and un-wack this for real.
2. Subject to the outcome of #1, you can approach this entirely in the NSString world, in which case I like Uli’s suggestion, applied to 'yourAttributedString.string as NSString’. You’d have to verify by performance testing that massive conversions aren’t being made.
_______________________________________________
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