快速元组到可选分配 [英] Swift tuple to Optional assignment

查看:74
本文介绍了快速元组到可选分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Swift编写一些代码来学习该语言.这是我的基类:

I am writing some code in Swift to learn the language. Here is my base class:

import Foundation
class BaseCommand:NSOperation
{
    var status:Int? = nil
    var message:String? = nil

    func buildRequest() -> NSData?
    {
        return nil
    }

    func parseResponse(data:NSData?) -> (Status:Int, Error:String)
    {
        return (200, "Success")
    }

    override func main() {
        let requestBody = self.buildRequest()

        println("Sending body \(requestBody)")
        // do network op
        var networkResultBody = "test"

        var resultBody:NSData = networkResultBody.dataUsingEncoding(NSUTF8StringEncoding)!
        (self.status, self.message) = self.parseResponse(resultBody)
    }
}

问题在最后一行:

(self.status, self.message) = self.parseResponse(resultBody)

编译器说无法将元组转换(Status:Int,Error:String)转换为(Int ?, String?)"

The compiler says "Cannot express tuple conversion (Status:Int, Error:String) to (Int?, String?)"

我知道问题在于self.status和self.message是可选的,而parseResponse不会返回Optionals(并且我不希望这样做).我如何告诉它进行必要的分配和转换,以将数据放入实例变量中?

I understand that the issue is that self.status and self.message are optionals, and the parseResponse does not return Optionals (and I don't want it to). How do I tell it to do the necessary assign and convert to get the data into the instance variables?

推荐答案

建议另一个答案(在更改之前)只是这样做:

Another answer suggested (before it was changed) to just do:

(self.status!, self.message!) = self.parseResponse(resultBody)

我发现这是不安全的.如果在分配时self.statusself.messagenil,它将崩溃.在Playground中尝试此测试:

I have found that is unsafe. It will crash if either self.status or self.message is nil at the time of the assignment. Try this test in a Playground:

class Test {
    var status: Int?
    var error: String?

    func parseResponse() -> (Status:Int, Error:String)
    {
        return (200, "Success")
    }

    func testIt() {
        (self.status!, self.error!) = parseResponse()
        print(self.status)
        print(self.error)
    }
}

let mytest = Test()
mytest.testIt()


这是另一种可以完成的方式:


Here is another way it could be done:

let (stat, err) = self.parseResponse(resultBody)
(self.status, self.error) = (Optional(stat), Optional(err))

或者,就像@AndriyGordiychuk发现的那样,它可以在没有Optional的情况下工作:

or, as @AndriyGordiychuk discovered, it works without Optional:

let (stat, err) = self.parseResponse(resultBody)
(self.status, self.error) = (stat, err)

这很好奇,但是分配函数的结果却没有.

It's curious that that works, but assigning the result of the function does not.

请注意以下实验:

var i: Int?
var s: String?

// This works
(i, s) = (3, "hello")

// This fails with error: cannot express tuple conversion '(Int, String)' to '(Int?, String?)
let t = (3, "hello")
(i, s) = t

似乎当分配是分配给元组的元组文字时,Swift会采用快捷方式并且不会首先构造该元组.相反,只是分配各个元素.

It seems that when the assignment is a tuple literal assigned to a tuple, Swift takes a shortcut and doesn't first construct the tuple. Instead, is just assigns the individual elements.

所以这个:

(i, s) = (3, "hello")

等效于:

i = 3
s = "hello"

之所以有效,是因为您可以将Int分配给Int?变量并将String分配给String?变量.元组分配失败,因为类型需要匹配.

which works because you can assign an Int to an Int? variable and a String to a String? variable. The tuple assignment fails because the types need to match.

这篇关于快速元组到可选分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆