I'm on this frustrating journey trying to get a specific character from a Swift string. I have an Objective-C function, something like
- ( NSString * ) doIt: ( char ) c
that I want to call from Swift.
This c
is eventually passed to a C function in the back that does the weightlifting here but this function gets tripped over when c
is
or A0
.
Now I have two questions (apologies SO).
I am trying to use different encodings, especially the
ASCII
variants, hoping one would convert
(A0
) to spcae (20
or dec 32). The verdict seems to be that I need to hardcode this but if there is a failsafe, non-hardcoded way I'd like to hear about it!I am really struggling with the conversion itself. How do I access a specific character using a specific encoding in Swift?
a) I can use
s.utf8CString[ i ]
but then I am bound to UTF8
.
b) I can use something like
let s = "\u{a0}"
let p = UnsafeMutablePointer < CChar >.allocate ( capacity : n )
defer
{
p.deallocate()
}
// Convert to ASCII
NSString ( string : s ).getCString ( p,
maxLength : n,
encoding : CFStringConvertEncodingToNSStringEncoding ( CFStringBuiltInEncodings.ASCII.rawValue ) )
// Hope for 32
let c = p[ i ]
but this seems overkill. The string is converted to NSString
to apply the encoding and I need to allocate a pointer, all just to get a single character.
c) Here it seems Swift String's withCString
is the man for the job, but I can not even get it to compile. Below is what Xcode's completion gives but even after fiddling with it for a long time I am still stuck.
// How do I use this
// ??
s.withCString ( encodedAs : _UnicodeEncoding.Protocol ) { ( UnsafePointer < FixedWidthInteger & UnsignedInteger > ) -> Result in
// ??
}
TIA
NSDiacriticInsensitiveSearch
. The string here represents a locale sensitive separator so I expect something like comma, space, semi etc. On the other question. The C chokes on A0 yes. So I need not really bother with the rest of the question, but I would love to see a real world example ofwithCString
. I've seen some simple ones on the net, nothing that uses an encoding. Then I can play around with it a bit and see if it will work or not.