有没有一种方法可以在Swift中为可选项创建一个计算属性?

huangapple go评论66阅读模式
英文:

Is there a way to have a computed property for optionals in Swift

问题

我在想是否有一种方法可以在可选值上实现一个计算属性,而不需要解包或默认值。为了举例说明,假设以下情况:

我们有一个UITextField的子类,我们想要添加一些验证。假设存在或不存在值(再次强调,这只是为了举例说明)。目前做到这一点的方法是:

var hasValue: Bool {
    if let value = text {
        return value.isEmpty
    } else {
        return false
    }
}

我尝试在Swift文档中搜索,但未能找到这样的内容。是否有人有更优雅的解决方案? 有没有一种方法可以在Swift中为可选项创建一个计算属性?

英文:

I was wondering if there is a way to achieve a computed property on an optional, which won't require unwrapping or default value. For the sake of the example, imagine the following scenario:

We have a subclass of UITextField and we want to add some sort of a validation. Let's say if there is a value or not (again, this is for the sake of the example). Right now the way to do so is:

var hasValue: Bool {
    if let value = text {
        return value.isEmpty
    } else {
        return false
    }
}

I've tried searching through the Swift documentation , but I was not able to find such thing. Does anyone have some more elegant solution to this? 有没有一种方法可以在Swift中为可选项创建一个计算属性?

答案1

得分: 0

当然可以:

extension Optional where Wrapped == String {
   var hasValue: Bool {
       return !(self ?? "").isEmpty
   }
}

然而,一般情况下,我会避免添加这样的方法,因为它们隐藏了变量是可选的事实。我更愿意显式地使用 (text ?? "").isEmpty

英文:

Of course you can:

extension Optional where Wrapped == String {
   var hasValue: Bool {
       return !(self ?? "").isEmpty
   }
}

However, in general I would avoid adding such methods because they hide the fact that a variable is optional. I would rather use the (text ?? "").isEmpty explicitly.

huangapple
  • 本文由 发表于 2023年6月19日 16:25:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定