英文:
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文档中搜索,但未能找到这样的内容。是否有人有更优雅的解决方案?
英文:
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?
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论