Reputation: 23
So, I was creating a converting app and I needed to use 2 IBActions. In one of them I made a constant and I tried to use it in the next one. But it doesn't work. How can I share the constant?
I am running Xcode 11. I have tried converting it into a variable but no success.
@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
}
I wanted to use the foo
constant in other IBAction but I am getting the Unresolved Identifier "foo"
.
Upvotes: 2
Views: 36
Reputation: 285079
Rule: All variables are only visible within the pair of braces they are declared in.
Declare the variable one level higher, and don't use NSString
in Swift
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) }
}
Upvotes: 2