Swift tuple to Optional assignment

David S.

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)
    }
}

The problem is on the last line:

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

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

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?

vacawama

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

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

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))

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.


Note the following experiment:

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

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.

So this:

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

is equivalent to:

i = 3
s = "hello"

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Optional assignment in Swift not working?

From Dev

Optional chaining used in left side of assignment in Swift

From Dev

Explicitly unwrapping an assignment to an optional property in Swift 2.2

From Dev

Swift switch statement on a tuple of optional booleans

From Dev

Swift switch statement on a tuple of optional booleans

From Dev

Swift optional variable assignment with default value (double question marks)

From Dev

Swift pattern matching with enum and Optional tuple associated values

From Dev

Why is it always possible to access the .0 element of an optional tuple in Swift?

From Dev

List comprehension with tuple assignment

From Dev

List comprehension with tuple assignment

From Dev

How to return an optional tuple

From Dev

Swift Optional of Optional

From Dev

Difference between list assignment and tuple assignment?

From Dev

Difference between list assignment and tuple assignment?

From Dev

How do I create an array of tuples in Swift where one of the items in the tuple is optional?

From Dev

Swift How to returning a tuple from a do catch where conditional binding must have optional type?

From Dev

dynamicType of optional chaining not the same as assignment

From Dev

Python assignment with optional result if not found

From Java

N long tuple as optional argument

From Dev

Weird optional tuple array behavior

From Dev

Swift: Optional Text In Optional Value

From Dev

Mutate tuple of lists getting "'tuple' object does not support item assignment“

From Dev

tuple as key to a dictionary says: 'tuple' object does not support item assignment

From Dev

Mutate tuple of lists getting "'tuple' object does not support item assignment“

From Dev

How the tuple unpacking differ from normal assignment?

From Dev

Python tuple assignment and checking in conditional statements

From Dev

Using unicode variables in Scala tuple assignment

From Dev

TypeError: 'tuple' object does not support item assignment

From Dev

Tuple matching vs. variable assignment in Python

Related Related

  1. 1

    Optional assignment in Swift not working?

  2. 2

    Optional chaining used in left side of assignment in Swift

  3. 3

    Explicitly unwrapping an assignment to an optional property in Swift 2.2

  4. 4

    Swift switch statement on a tuple of optional booleans

  5. 5

    Swift switch statement on a tuple of optional booleans

  6. 6

    Swift optional variable assignment with default value (double question marks)

  7. 7

    Swift pattern matching with enum and Optional tuple associated values

  8. 8

    Why is it always possible to access the .0 element of an optional tuple in Swift?

  9. 9

    List comprehension with tuple assignment

  10. 10

    List comprehension with tuple assignment

  11. 11

    How to return an optional tuple

  12. 12

    Swift Optional of Optional

  13. 13

    Difference between list assignment and tuple assignment?

  14. 14

    Difference between list assignment and tuple assignment?

  15. 15

    How do I create an array of tuples in Swift where one of the items in the tuple is optional?

  16. 16

    Swift How to returning a tuple from a do catch where conditional binding must have optional type?

  17. 17

    dynamicType of optional chaining not the same as assignment

  18. 18

    Python assignment with optional result if not found

  19. 19

    N long tuple as optional argument

  20. 20

    Weird optional tuple array behavior

  21. 21

    Swift: Optional Text In Optional Value

  22. 22

    Mutate tuple of lists getting "'tuple' object does not support item assignment“

  23. 23

    tuple as key to a dictionary says: 'tuple' object does not support item assignment

  24. 24

    Mutate tuple of lists getting "'tuple' object does not support item assignment“

  25. 25

    How the tuple unpacking differ from normal assignment?

  26. 26

    Python tuple assignment and checking in conditional statements

  27. 27

    Using unicode variables in Scala tuple assignment

  28. 28

    TypeError: 'tuple' object does not support item assignment

  29. 29

    Tuple matching vs. variable assignment in Python

HotTag

Archive