SwiftUI - 多次重复

SwiftUI - Multiple Repetitions

我需要为一年中的每一天显示特定的文本,当我将代码重复大约 30 次时,一切都很好,如果我将每天的代码扩展 365 次,就会出现错误。

代码:

if ("\(formatDate(date: today))") .elementsEqual("01-01"){
                                Text("Lucy")
                            }
                    else if ("\(formatDate(date: today))") .elementsEqual("02-01"){
                                Text("Karl")
                            }
                    else if ("\(formatDate(date: today))") .elementsEqual("03-01"){
                                Text("Jack")
                            }
                    else if ("\(formatDate(date: today))") .elementsEqual("04-01"){
                                Text("Tim")
                            }
                    else if ("\(formatDate(date: today))") .elementsEqual("05-01"){
                                Text("Sarah")
                            }
// and so on ... 365x

错误:

The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

最有可能发生的情况是您的程序效率太低。 如果我没有正确理解你的问题,我会这样做:

var texts = ["Lucy", "Karl", "Jack", "Tim", "Sarah"] //and so on with whatever texts you are using.
for x in 1...365 {
   if x < 10 {
      if ("\(formatDate(date: today))") .elementsEqual("0\(x)-01"){
                                Text("\(texts[x-1])")
                            }
   } else {
      if ("\(formatDate(date: today))") .elementsEqual("\(x)-01"){
                                Text("\(texts[x-1])")
                            }
   }

}

我认为最简单的方法是设置一个 Dictionary<String,String>,其中键是格式化日期,值是结果文本:

let dateTextDictionary = [
    "01-01":"Lucy",
    "02-01":"Karl",
    "03-01":"Tim",
]
if let resultText = dateTextDictionary[formatDate(date: today)] {
    Text(resultText)
}

也可以从 JSON 文件或 plist 加载此词典。