如何检查值是否为真?
How to check if value is true?
我有一个结构:
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()
如何检查 format.bold == true 或 format.italic == true 的值,基本上我想检查结构中的哪个值是 true 并只打印 true 的值?
首先不需要init方法
要打印 true
值,一个可能的解决方案是添加计算的 属性
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: ", ")
}
}
当然还有其他方法。
你走错路了,你需要的是枚举:
enum TextFormat: String, CaseIterable, CustomStringConvertible {
case bold, italic, underline, strikethrough
var description: String { rawValue }
}
现在您可以创建集合了:
let formats: Set<TextFormat> = [.bold, .italic]
print("formats:", formats)
print("all formats:", TextFormat.allCases)
print("is bold:", formats.contains(.bold))
这将打印:
formats: [italic, bold]
all formats: [bold, italic, underline, strikethrough]
is bold: true
我有一个结构:
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()
如何检查 format.bold == true 或 format.italic == true 的值,基本上我想检查结构中的哪个值是 true 并只打印 true 的值?
首先不需要init方法
要打印 true
值,一个可能的解决方案是添加计算的 属性
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: ", ")
}
}
当然还有其他方法。
你走错路了,你需要的是枚举:
enum TextFormat: String, CaseIterable, CustomStringConvertible {
case bold, italic, underline, strikethrough
var description: String { rawValue }
}
现在您可以创建集合了:
let formats: Set<TextFormat> = [.bold, .italic]
print("formats:", formats)
print("all formats:", TextFormat.allCases)
print("is bold:", formats.contains(.bold))
这将打印:
formats: [italic, bold]
all formats: [bold, italic, underline, strikethrough]
is bold: true