Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if value is true?

I have a struct:

public struct TextFormat: Equatable {

  var bold: Bool
  var italic: Bool
  var underline: Bool
  var strikethrough: Bool

  public init() {
    self.bold = false
    self.italic = false
    self.underline = false
    self.strikethrough = false
  }
}

var format: TextFormat = TextFormat()

How do I check if the value of format.bold == true or format.italic == true, basically I want to check which value in the struct is true and print only the value that’s true?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First of all the init method is not needed

To print the true values a possible solution is to add a computed property

public struct TextFormat: Equatable {
    var bold = false
    var italic = false
    var underline = false
    var strikethrough = false
    
    var status : String {
        var result = [String]()
        if bold { result.append("bold") }
        if italic { result.append("italic") }
        if underline { result.append("underline") }
        if strikethrough { result.append("strikethrough") }
        return result.joined(separator: ", ")
    }
}

Certainly there are other ways.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading