是否有一種方法可以將條件賦值賦給Swift的常數?

[英]Is there a way to do conditional assignment to constants in Swift?


I would like to create an immutable value that is assigned different values depending on a condition. In Scala I would be able to write the following:

我希望創建一個不可變的值,根據條件指定不同的值。在Scala里,我可以寫下以下內容:

    let attribs = if #available(iOS 8.2, *) {
        [ NSFontAttributeName: UIFont.systemFontOfSize(30, weight: UIFontWeightLight) ]
    } else {
        [ NSFontAttributeName: UIFont.systemFontOfSize(30) ]
    }

but since Swift if statements don't return the result of the executed code block that doesn't work.

但是由於Swift if語句不返回已執行代碼塊的結果,所以無法工作。

If the test was for a normal Bool I could use the ternary conditional operator

如果測試的是一個正常的Bool,我可以使用三元條件運算符

    let attribs = #available(iOS 8.2, *) ?
        [ NSFontAttributeName: UIFont.systemFontOfSize(30, weight: UIFontWeightLight) ]
    :
        [ NSFontAttributeName: UIFont.systemFontOfSize(30) ]

but that doesn't work for the iOS version tests, I get the following error:

但這對iOS版本測試不適用,我得到如下錯誤:

#available may only be used as condition of an 'if', 'guard' or 'while' statement.

I feel like I'm stuck with a var, but unless I also make it optional I end up with a double assignment in most cases, which seems so ugly and unnecessary?

我覺得我被困在一個var中了,但是除非我也把它設定為可選的,否則我在大多數情況下都會得到一個雙重的賦值,這看起來是如此的丑陋和不必要?

    var attribs = [ NSFontAttributeName: UIFont.systemFontOfSize(30) ]
    if #available(iOS 8.2, *) {
        [ NSFontAttributeName: UIFont.systemFontOfSize(30, weight: UIFontWeightLight) ]
    }

Thanks for any help!

感謝任何幫助!

3 个解决方案

#1


8  

Do the declaration and assignment on two separate lines:

在兩條單獨的線上做聲明和分配:

let attribs: [String: Any]
if #available(iOS 8.2, *) {
    attribs = [NSFontAttributeName: UIFont.systemFontOfSize(30, weight: UIFontWeightLight)]
} else {
    attribs = [NSFontAttributeName: UIFont.systemFontOfSize(30)]
}

Even though it is a let, you can do the assignment (only once per path of control) on a separate line.

即使是一個let,您也可以在單獨的行上執行賦值(每個控件路徑只執行一次)。

#2


4  

I think you want something like this:

我想你想要這樣的東西:

let value: String
if #available(iOS 9, *) {
    value = "iOS 9 is available"
} else {
    value = "iOS 9 and up only"
}
print(value) // iOS 9 is available

#3


1  

You could also do this

你也可以這么做

var someConstant:String {
    if #available(iOS 9, *) {
        return "iOS 9"
    } else {
        return"not iOS 9"
    }
}

by doing this you can't assign a value to the variable someConstant even if it is a var and not a let because it is a calculated property

通過這樣做,即使變量是var而不是let,你也不能為它賦值,因為它是一個計算屬性


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/12/03/720e19835cd917e2ed445659641a2553.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com