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

error while converting NSData objectiveC code to swift

我尝试将 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,并检查可失败初始化器 return 是否有值

您要查找的方法NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)不存在。

你可以这样转换

var data = NSData(data :response.dataUsingEncoding(NSASCIIStringEncoding)!)


已更新

方法 outputStream.write() 需要 UInt8[] 数组,因此您必须将数据转换为 UInt8[] Array

您的代码应该是,

@IBAction func sendMessage() {
    var response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
    var data = NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)        
    outputStream.write(UnsafePointer(data.bytes), maxLength:data.length)
    inputMessageField?.text = ""
}