2

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).

  1. 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!

  2. 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

5
  • 1
    “Nonbreaking space” U+A0 and “Space” U+20 are different characters, so this is not an encoding problem. You could simply replace one by the other before extracting the C characters.
    – Martin R
    Jan 23, 2021 at 7:58
  • @MartinR thanks - is what I do at present. But still, to get just one char from a Swift string in a given encoding ...
    – skaak
    Jan 23, 2021 at 8:04
  • Are there more problematic characters? What about umlauts, symbols, emojis, ...? How would you expect those to be handled?
    – Martin R
    Jan 23, 2021 at 8:17
  • Another question: It the problem that the C function chokes on A0, or that it is converted to UTF-8 (C2 A0)?
    – Martin R
    Jan 23, 2021 at 8:24
  • @MartinR I don't really have that umlaut problem but if I run into it I suppose more hardcoded replacements using e.g. 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 of withCString. 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.
    – skaak
    Jan 23, 2021 at 8:29

1 Answer 1

1

There are two withCString() methods: withCString(_:) calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of UTF-8 code units. Example:

// An emulation of your Objective-C method.
func doit(_ c: CChar) {
    print(c, terminator: " ")
}

let s = "a\u{A0}b"
s.withCString { ptr in
    var p = ptr
    while p.pointee != 0 {
        doit(p.pointee)
        p += 1
    }
}
print()

// Output: 97 -62 -96 98

Here -62 -96 is the signed character representation of the UTF-8 sequence C2 A0 of the NO-BREAK SPACE character U+00A0.

If you just want to iterate over all UTF-8 characters of the string sequentially then you can simply use the .utf8 view. The (unsigned) UInt8 bytes must be converted to the corresponding (signed) CChar:

let s = "a\u{A0}b"
for c in s.utf8 {
        doit(CChar(bitPattern: c))
}
print()

I am not aware of a method which transforms U+00A0 to a “normal” space character, so you have to do that manually. With

let s = "a\u{A0}b".replacingOccurrences(of: "\u{A0}", with: " ")

the output of the above program would be 97 32 98.

The withCString(encodedAs:_:) method calls the given closure with a pointer to the contents of the string, represented as a null-terminated sequence of code units. Example:

let s = "a\u{A0}b€"
s.withCString(encodedAs: UTF16.self) { ptr in
    var p = ptr
    while p.pointee != 0 {
        print(p.pointee, terminator: " ")
        p += 1
    }
}
print()

// Output: 97 160 98 8364

This method is probably of limited use for your purpose because it can only be used with UTF8, UTF16 and UTF32.

For other encodings you can use the data(using:) method. It produces a Data value which is a sequence of UInt8 (an unsigned type). As above, these must be converted to the corresponding signed character:

let s = "a\u{A0}b"
if let data = s.data(using: .isoLatin1) {
    data.forEach {
        doit(CChar(bitPattern: $0))
    }
}
print()

// Output: 97 -96 98

Of course this may fail if the string is not representable in the given encoding.

2
  • Thanks Martin, I appreciate your efforts. Especially the withCString example and also the extra mile you went with the data one.
    – skaak
    Jan 23, 2021 at 10:13
  • @skaak: You are welcome. I have added another method for c in s.utf8 { ... } which is even simpler to use and may be sufficient for your purpose.
    – Martin R
    Jan 23, 2021 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.