Josef Zoller
Josef Zoller

Reputation: 951

swift struct nested in function

Just for fun I tested out, if such a function is actually working:

func exampleFunction() -> Any {
    struct Example {
        let x: Int
    }
    let example = Example(x: 2)
    return example
}

And surprisingly it is. My question is now: Is it able to access for example x from the function? Of course this doesn't work:

let example = exampleFunction()
print(example.x)         
//Error: Value of type 'Any' has no member 'x'

It has to be type casted first, but with which type?

let example = exampleFunction()
print((example as! Example).x)
//Of course error: Use of undeclared type 'Example'

print((example as! /* What to use here? */).x)

Surprisingly print(type(of: example)) prints the correct string Example

Upvotes: 3

Views: 2122

Answers (1)

vacawama
vacawama

Reputation: 154563

As @rmaddy explained in the comments, the scope of Example is the function and it can't be used outside of the function including the function's return type.

So, can you get at the value of x without having access to the type Example? Yes, you can if you use a protocol to define a type with a property x and have Example adopt that protocol:

protocol HasX {
    var x: Int { get }
}

func exampleFunction() -> Any {
    struct Example: HasX {
        let x: Int
    }
    let example = Example(x: 2)

    return example
}

let x = exampleFunction()
print((x as! HasX).x)
2

In practice, this isn't really an issue. You'd just define Example at a level that is visible to the function and any callers.

Upvotes: 6

Related Questions