Search code examples
swiftstructbooleanappend

How to append Bool value of a struct in Swift


So, I'm coding in Swift and I've made a struct called User. It has four categories of characteristics- name, email, number of followers, and activity status. I am able to append values of the variables of the structs I create without issue, so long as they are Strings or Ints, Dicts etc. It won't let me append the value of the Bool. I initially set it to 'true', but I'd like to append it to being 'false' after initializing it. I'm getting the error message: "Value of type 'Bool' has no member 'append'". I get that I'm not allowed to append it the same way as I can with say User.name.append("Tim"), but what I don't get is how I actually can append it. Google was unhelpful,searching in SO also yielded nothing of note, and Apple documentation on Structs shows them setting similar values in their explanation at the beginning using Strings and Bools and appending the Strings but not appending the Bools. I can't imagine it not being possible as things change all the time from true to false status, depending on the situation. If I remove the line below, it compiles fine.

userTwo.isAcctive.append(false) is where my error is, for clarity.

Any help would be appreciated!

struct User {
  let name: String
  let email: String?
  var followers: Int
  var isActive: Bool

  init(name: String, email: String, followers: Int, isActive: Bool){
    self.name = name
    self.email = email
    self.followers = followers
    self.isActive = isActive
  }

  func logStatus(){
    if isActive == true{
    print("\(name) is working hard.")
    } else {
      print("\(name) has left the earth.")
    }
  }
}

var userOne = User(name: "Richard", email:("") , followers: 0, isActive: false)

var userTwo = User(name: "Elon", email:("[email protected]") , followers: 2100, isActive: true)
print(userTwo.isActive)
userTwo.isActive.append(false)

userOne.logStatus()
userTwo.logStatus()

Solution

  • Appending is to add a new element to an array. I think you want to change isActive property. You can do this by:

    var userTwo = User(name: "Elon", email:("[email protected]") , followers: 2100, isActive: true)
    userTwo.isActive = false