简体   繁体   English

更短的替代三元以生成空字符串如果为零?

[英]Shorter Alternative to ternary to generate empty string if nil?

I have a parameter of Type Double?我有一个类型为Double?的参数Double? . . When this parameter is nil , I want to have an empty string.当此参数为nil ,我想要一个空字符串。

I can use if (variable == nil) ? "" : String(variable!)我可以使用if (variable == nil) ? "" : String(variable!) if (variable == nil) ? "" : String(variable!) but is there a shorter alternative? if (variable == nil) ? "" : String(variable!)但有更短的选择吗?

Using Optional.map and the nil-coalescing operator ??使用Optional.map和 nil-coalescing 运算符?? you can do你可以做

var variable: Double? = 1.0
let string = variable.map { String($0) } ?? ""

The closure is called (and the string returned) if the variable is not nil , otherwise map returns nil and the expression evaluates to the empty string.如果变量不是nil ,则调用闭包(并返回字符串),否则map返回nil并且表达式计算为空字符串。

I don't see a simple way to simplify your code.我没有看到简化代码的简单方法。 An idea is to create a Double extension like this:一个想法是创建一个像这样的双扩展:

extension Optional where Wrapped == Double {
    var asString: String {
        self == nil ? "" : String(self!)
    }
}

And then instead of that if condition you just use:然后,而不是使用 if 条件:

variable.asString

If you want to use the resulting string in another string, like this:如果你想在另一个字符串中使用结果字符串,像这样:

let string = "The value is: \\(variable)"

and possibly specify what to print when variable is nil :并可能指定variable nil时要打印的内容:

let string = "The value is: \\(variable, nil: "value is nil")"

you can write a handy generic extension for String.StringInterpolation which takes any type of value and prints this and if it's an optional and also nil it prints the specified "default" string:你可以为 String.StringInterpolation 编写一个方便的通用扩展,它接受任何类型的值并打印它,如果它是一个可选的并且也是nil它打印指定的“默认”字符串:

extension String.StringInterpolation {
    mutating func appendInterpolation<T>(_ value: T?, `nil` defaultValue: @autoclosure () -> String) {
        if let value = value {
            appendLiteral("\(value)")
        } else {
            appendLiteral(defaultValue())
        }
    }
}

Example:例子:

var d: Double? = nil
print("Double: \(d, nil: "value is nil")")

d = 1
print("Double: \(d, nil: "value is nil")")

let i = 1
print("Integer: \(i, nil: "value is nil")")

Output on the console:控制台输出:

Double: value is nil
Double: 1.0
Integer: 1

Just for fun a generic approach to cover all types that conforms to LosslessStringConvertible:只是为了好玩,一种涵盖所有符合 LosslessStringConvertible 类型的通用方法:

extension LosslessStringConvertible {
    var string: String { .init(self) }
}

extension Optional where Wrapped: LosslessStringConvertible {
    var string: String { self?.string ?? "" }
}

var double = Double("2.7")

print(double.string)    // "2.7\n"

Property wrappers should help you give the desired result - property wrappers have a special variables wrappedValue and projectedValue that can add a layer of separation and allow you to wrap your custom logic.属性包装器应该可以帮助您提供所需的结果 - 属性包装器有一个特殊的变量wrapperValueprojectedValue ,它们可以添加一个分离层并允许您包装自定义逻辑。

wrappedValue - manipulate this variable with getters and setters. wrappedValue - 使用 getter 和 setter 操作此变量。 It has very less use in our case as it is of Double?在我们的情况下,它的用途很少,因为它是 Double? type类型

projectedValue - this is going to be our focus as we can use this variable to project the Double as a String in our case.投影值- 这将是我们的重点,因为在我们的例子中,我们可以使用这个变量将 Double 投影为字符串。

The implementation is as below实现如下

@propertyWrapper
struct DoubleToString {
    private var number: Double = 0.0
    var projectedValue: String = ""
    var wrappedValue: Double?{
        get {
            return number // Not really required
        }
        set {
            if let value = newValue { // Check for nil
                projectedValue = value.description // Convert to string
                number = value
            } 
        }
    }
}

Now we create a struct which uses this wrapper.现在我们创建一个使用这个包装器的结构。

struct NumbersTest {
    @DoubleToString var number1: Double?
    @DoubleToString var number2: Double?
}

On running the below code, we get the desired result.在运行下面的代码时,我们得到了想要的结果。 $number1 gives us the projectedValue and if we ignore the $ symbol we get the wrappedvalue $number1 为我们提供了projectedValue ,如果我们忽略$ 符号,我们将获得wrappedvalue

var numbersTest = NumbersTest()
numbersTest.number1 = 25.0
numbersTest.number2 = nil

print(numbersTest.$number1) //"25.0"
print(numbersTest.$number2) //""

By using property wrappers you can keep the variable interoperable to get both Double and String values easily.通过使用属性包装器,您可以保持变量的互操作性,以便轻松获取 Double 和 String 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM