1

When I searched on here I now know that almost everything in Swift is value based, not referenced base. I also have read that a class holds references. I tried my best, but below code will not print anything. If anyone could help me out printing out that line with the help of an array, that would be great :) (if it is possible ofcourse...).

Edit: I want 5 booleans in the array, in which they all have a didSet method. When I access them, that specific didSet will trigger. Is that possible?

class PowerUpBooleans{
    var boolean: Bool
    init(boolean: Bool){
        self.boolean = boolean
    }
}
var iWantToChangeThis = false{
        didSet{
            print("it worked")
        }
    }
    var powerUpBooleans = [PowerUpBooleans]()
override func viewDidLoad() {
        super.viewDidLoad()
        powerUpBooleans.append(PowerUpBooleans(boolean: iWantToChangeThis))
        powerUpBooleans[0].boolean = true
     }
5
  • 1
    Bool is pass by value, not by reference Commented Aug 11, 2017 at 1:20
  • @koropok yes but is there any to keep a reference to that boolean in an array? Or is this not possible at all? Thank you. Commented Aug 11, 2017 at 1:23
  • you can try the answer below, or use inout. Commented Aug 11, 2017 at 1:27
  • @koropok I will search for inout methods. I editted my question to make it more clear what I want. I want to have a didSet method on all the variables. Commented Aug 11, 2017 at 1:35
  • you can check this out. stackoverflow.com/questions/40745099/… Commented Aug 11, 2017 at 1:36

1 Answer 1

3

I guess you want set some booleans that have their own trigger.

As I known, making value type wrapped by class can only make it be reference type.

So try this.

class PowerUpBooleans{
  var boolean: Bool {
    didSet {
      trigger()
    }
  }
  var trigger: () -> ()

  init(boolean: Bool, trigger: @escaping () -> ()){
    self.boolean = boolean
    self.trigger = trigger
  }
}

let trigger1 = {
  print("one worked.")
}
let trigger2 = {
  print("two worked.")
}

var powerUpBooleans = [PowerUpBooleans]()
powerUpBooleans.append(PowerUpBooleans(boolean: false, trigger: trigger1))
powerUpBooleans.append(PowerUpBooleans(boolean: false, trigger: trigger2))
powerUpBooleans[0].boolean = true   // print one worked
powerUpBooleans[1].boolean = false  // print two worked
Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.