所以我试图将一些obj-c代码转换为swift,但我仍然坚持使用它的一部分。 我如何在swift中做这样的事情?
- (void)sometMethod:(NSString *)s {
NSString * crlfString = [s stringByAppendingString:@"\r\n"];
uint8_t *buf = (uint8_t *)[crlfString UTF8String];}
真正的问题是这一行
uint8_t *buf = (uint8_t *)[crlfString UTF8String];
答案 0 :(得分:2)
你想用UTF-8缓冲区做什么?通常,将字符串直接转换为NSData
对象会更方便。但是你也可以将你的Obj-C代码逐个翻译成Swift。以下是两种变体:
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
如果您想迭代UTF-8代码单元而不处理缓冲区,请使用以下内容:
for codeUnit in String.utf8 {
println(codeUnit)
}