Nuno
Nuno

Reputation: 525

obj-c to Swift convert code

So I'm trying to convert some obj-c code into swift but I'm stuck on a part of it. How can I do something like this in swift?

- (void)sometMethod:(NSString *)s {
NSString * crlfString = [s stringByAppendingString:@"\r\n"];
uint8_t *buf = (uint8_t *)[crlfString UTF8String];}

The real problem is this line

uint8_t *buf = (uint8_t *)[crlfString UTF8String];

Upvotes: 0

Views: 1046

Answers (1)

Ole Begemann
Ole Begemann

Reputation: 135578

What do you want to do with the UTF-8 buffer? Generally, it is more convenient to convert the string directly to an NSData object. But you can also translate your Obj-C code one by one to Swift. Here are both variants:

import Foundation

func appendCRLFAndConvertToUTF8_1(s: String) -> NSData {
    let crlfString: NSString = s.stringByAppendingString("\r\n")
    let buffer = crlfString.UTF8String
    let bufferLength = crlfString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
    let data = NSData(bytes: buffer, length: bufferLength)
    return data;
}

func appendCRLFAndConvertToUTF8_2(s: String) -> NSData {
    let crlfString = s + "\r\n"
    return crlfString.dataUsingEncoding(NSUTF8StringEncoding)!
}

let s = "Hello 😄"
let data1 = appendCRLFAndConvertToUTF8_1(s)
data1.description

let data2 = appendCRLFAndConvertToUTF8_2(s)
data2.description

data1 == data2

And if you want to iterate over the UTF-8 code units and not deal with a buffer, use something like:

for codeUnit in String.utf8 {
    println(codeUnit) 
}

Upvotes: 2

Related Questions