gpt4 book ai didi

objective-c - 将 NSData objectiveC 代码转换为 swift 时出错

转载 作者:搜寻专家 更新时间:2023-10-31 23:04:25 24 4
gpt4 key购买 nike

我尝试将 Objective C 中的这段代码转换为 Swift,

- (IBAction) sendMessage {

NSString *response = [NSString stringWithFormat:@"msg:%@", inputMessageField.text];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
inputMessageField.text = @"";

}

下面是我的swift代码。

@IBAction func sendMessage() {

var response = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
var data = NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)
outputStream(write:data.bytes, maxLength:data.length);
inputMessageField?.text = ""

}

我收到一条错误消息,告诉我数据是一个额外的参数。请帮我解决这个问题。

最佳答案

没有 NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding) 方法。您可能正在寻找

let data = 
response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

你的整个代码应该是这样的:

let response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
if let data = response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
outputStream(write:data.bytes, maxLength:data.length);
inputMessageField?.text = ""
}
else {
println("could not convert response \"\(response)\" to NSData")
}

尽可能使用 let,并检查可失败的初始化器是否返回值

关于objective-c - 将 NSData objectiveC 代码转换为 swift 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27938729/

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