我想创建一个根据条件分配不同值的不可变值.在
Scala我可以写下列内容:
let attribs = if #available(iOS 8.2,*) { [ NSFontAttributeName: UIFont.systemFontOfSize(30,weight: UIFontWeightLight) ] } else { [ NSFontAttributeName: UIFont.systemFontOfSize(30) ] }
但是由于Swift if语句不返回执行代码块的结果不起作用.
如果测试是针对正常的Bool,我可以使用三元条件运算符
let attribs = #available(iOS 8.2,*) ? [ NSFontAttributeName: UIFont.systemFontOfSize(30,weight: UIFontWeightLight) ] : [ NSFontAttributeName: UIFont.systemFontOfSize(30) ]
但是这不适用于iOS版本测试,我收到以下错误:
#available may only be used as condition of an 'if','guard' or 'while' statement.
我觉得我被卡住了一个var,但是除非我也可以选择我在多数情况下最终得到一个双重任务,这似乎是如此丑陋和不必要?
var attribs = [ NSFontAttributeName: UIFont.systemFontOfSize(30) ] if #available(iOS 8.2,weight: UIFontWeightLight) ] }
感谢任何帮助!
解决方法
在两个单独的行上进行声明和分配:
let attribs: [String: Any] if #available(iOS 8.2,*) { attribs = [NSFontAttributeName: UIFont.systemFontOfSize(30,weight: UIFontWeightLight)] } else { attribs = [NSFontAttributeName: UIFont.systemFontOfSize(30)] }
即使它是一个let,你可以在一个单独的行上进行分配(每个控制路径只有一次).