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?
CodePudding user response:
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.
CodePudding user response:
You are going the wrong way what you need here is an enumeration:
enum TextFormat: String, CaseIterable, CustomStringConvertible {
case bold, italic, underline, strikethrough
var description: String { rawValue }
}
Now you can create a set:
let formats: Set<TextFormat> = [.bold, .italic]
print("formats:", formats)
print("all formats:", TextFormat.allCases)
print("is bold:", formats.contains(.bold))
This will print:
formats: [italic, bold]
all formats: [bold, italic, underline, strikethrough]
is bold: true