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?
(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))
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With