gpt4 book ai didi

objective-c - obj-c 到 Swift 转换代码

转载 作者:行者123 更新时间:2023-11-28 13:21:45 25 4
gpt4 key购买 nike

所以我正在尝试将一些 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];

最佳答案

你想用 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)
}

关于objective-c - obj-c 到 Swift 转换代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24907143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com