How do you change an outside variable inside a function with passing a parameter?; Noobie in swift
var varIsTrue:Bool = true
import UIKit
extension UIDevice {
class ViewController: UIViewController {
override func viewDidLoad() {
changeVar(varIsTrue , false)
}
func changeVar(_ varName:? , _ arg:Bool){
varName = arg // Xcode cannot assign to value: 'varName' is a 'let' constant
}
// varName:? Don't know if the question mark should be a :String some kind of argument or what?
}
}
Assuming your example is just an abstraction and you're trying to understand the concept of changing a variable from within a function this would be a solution.
Like already mentioned in the comments you need to use inout
and pass the reference (indicated by the leading &
) of your "outside variable".
var varIsTrue: Bool = true
changeVar(&varIsTrue , false)
func changeVar(_ property: inout Bool , _ arg: Bool){
property = arg
}