hkatz hkatz - 9 months ago 49
Swift Question

Why does Xcode report "Variable 'tuple.0' used before being initialized" after I've assigned all elements of a Swift tuple?

I want to assign the 3 numbers in an array to the 3 elements of a tuple using a

loop. The following function seems to do the trick, but Xcode errors as soon as I try to reference the (seemingly) fully assigned tuple. Am I doing something wrong?

typealias Triple = (Int, Int, Int)
func createTuple() -> Triple
var tuple: Triple
let r = [8, 6, 3]

for i in 0..<r.count {
switch(i) {
case 0: tuple.0 = r[i]
case 1: tuple.1 = r[i]
case 2: tuple.2 = r[i]
default : break
return tuple // Xcode says "Variable 'tuple.0' used before being initialized

Answer Source

The problem of determining whether a variable can be guaranteed to have been assigned or not is not decidable for the general case. This can be proven by a transformation on the halting problem. If you want to know more about that, I suggest you post a question on the Computer Science stack exchange site.

The Swift compiler approximates the solution to this problem by handling specific cases. Your case is not one of those handled by the Swift compiler (yet)?

If you just want to assign the triple, you can do this:

typealias Triple = (Int, Int, Int)
func createTriple() -> Triple {
    return (8, 6, 3)

If you want to assign it from an array, it's a lot simpler without the loop and switch (for the case of just 3 components)

typealias Triple = (Int, Int, Int)
func createTriple(from array: [Int]) -> Triple {
    guard array.count > 3 else {
       fatalError("Can't create a triple from less than 3 elements")
    return (array[0], array[1], array[2])