Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 449
Josef Zoller Avatar asked Oct 23 '25 13:10

Josef Zoller


1 Answers

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.

like image 82
vacawama Avatar answered Oct 26 '25 03:10

vacawama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!