所以,我正在创建一个转换应用程序,需要使用2个Ibactions。在其中一个,我做了一个常数,我试图在下一个中使用它。但这无效。我如何共享常数?
我正在运行Xcode 11.我尝试将其转换为变量,但没有成功。
@IBAction func select(_ sender: Any) {
let foo = "/some/cool/path.txt"
}
@IBAction func convert(_ sender: Any) {
let contents = try NSString(contentsOfFile: foo, encoding: NSUTF8StringEncoding) // And here comes the error
}
我想在其他IBACTION中使用foo
常数,但我正在获得Unresolved Identifier "foo"
。
规则:所有变量仅在声明的一对括号中可见。
声明变量一个级别更高,并且不要在Swift
中使用NSString
var foo = ""
@IBAction func select(_ sender: Any) {
foo = "/some/cool/path.txt"
}
@IBAction func convert(_ sender: Any) {
do {
let contents = try String(contentsOfFile: foo, encoding: .utf8)
} catch { print(error) }
}