Jos*_*ler 2 struct nested function swift
只是为了好玩,我测试了一下,如果这样的功能真的有效:
func exampleFunction() -> Any {
struct Example {
let x: Int
}
let example = Example(x: 2)
return example
}
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是。我现在的问题是:它是否能够例如x从函数访问?当然这是行不通的:
let example = exampleFunction()
print(example.x)
//Error: Value of type 'Any' has no member 'x'
Run Code Online (Sandbox Code Playgroud)
它必须先进行类型转换,但使用哪种类型?
let example = exampleFunction()
print((example as! Example).x)
//Of course error: Use of undeclared type 'Example'
print((example as! /* What to use here? */).x)
Run Code Online (Sandbox Code Playgroud)
出人意料地print(type(of: example))打印出正确的字符串Example
正如@rmaddy 在评论中解释的那样,范围Example是函数,不能在函数之外使用,包括函数的返回类型。
那么,您能否在x无法访问类型的情况下获得 的值Example?是的,如果您使用 aprotocol来定义具有属性的类型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)
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)2
在实践中,这并不是真正的问题。您只需Example在对函数和任何调用者可见的级别进行定义。