[英]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? 我的问题现在是:它是否可以从该函数访问
x
? 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
令人惊讶的
print(type(of: example))
打印正确的字符串Example
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. 正如@rmaddy在评论中解释的那样,
Example
的范围是函数,不能在包含函数的返回类型的函数外部使用。
So, can you get at the value of x
without having access to the type Example
? 因此,无需访问
Example
类型就可以得到x
的值吗? Yes, you can if you use a protocol
to define a type with a property x
and have Example
adopt that protocol
: 是的,如果您使用
protocol
定义具有属性x
的类型并让Example
该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. 您只需在函数和所有调用者可见的级别上定义
Example
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.