Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4: tuple as optional

Tags:

swift

tuples

New to swift. From what I understand, tuple assignment operator '?' isn't allow with tuple.

var optionalTuple = (String, Int)? // this isn't allowed.  

Is there a work around besides assigning the elements as optional individually?

like image 297
seems Avatar asked Dec 10 '25 17:12

seems


2 Answers

(String, Int)? is a type, not a value, so it cannot be put on the right hand side of =.

If you didn't know already, when you declare a variable/constant, you can specify its type using this syntax:

let/var name: Type

So an optional tuple declaration looks like this:

var optionalTuple: (String, Int)?

Another way to do it is this:

var optionalTuple = (String, Int)?.none

The above two will have the value of nil. You can also initialise this to a custom value:

var optionalTuple: (String, Int)? = ("Hello", 10)

Another way to do this is:

var optionalTuple = (String, Int)?.some(("Hello", 10))
like image 173
Sweeper Avatar answered Dec 13 '25 19:12

Sweeper


Tuples can be declared as optional, but you seem to be confusing the type and the value.

//Type is optional tuple (String, Int), value is nil
let optionalTuple : (String, Int)? = nil       

//Type is optional tuple (String, Int), value is ("James", 27)
let optionalTuple : (String, Int)? = ("James", 27)   

//Type is (inferred) optional tuple (String, Int). Value is ("James", 27)
let optionalTuple = ("James", 27)       

With some unit tests so you can run and see for yourself:

func testTupleOptionality() {

    func returnOptionalTuple(returnNil:Bool) -> (String, Int)? {
        if returnNil {
            return nil
        }
        else {
            return ("James", 27)
        }
    }

    let result1 = returnOptionalTuple(returnNil: true)
    XCTAssertNil(result1)

    let result2 = returnOptionalTuple(returnNil: false)
    XCTAssertNotNil(result2)
    XCTAssertEqual(result2!.0, "James")
    XCTAssertEqual(result2!.1, 27)
}

func testTupleOptionalityVariable() {
    let optionalTuple : (String, Int) = nil
    XCTAssertNil(optionalTuple)
}             
like image 25
James Webster Avatar answered Dec 13 '25 17:12

James Webster