Check string for nil & empty

后端 未结 23 1321
感动是毒
感动是毒 2020-12-07 10:53

Is there a way to check strings for nil and \"\" in Swift? In Rails, I can use blank() to check.

I currently have this, but i

23条回答
  •  自闭症患者
    2020-12-07 11:12

    With Swift 5, you can implement an Optional extension for String type with a boolean property that returns if an optional string is empty or has no value:

    extension Optional where Wrapped == String {
    
        var isEmptyOrNil: Bool {
            return self?.isEmpty ?? true
        }
    
    }
    

    However, String implements isEmpty property by conforming to protocol Collection. Therefore we can replace the previous code's generic constraint (Wrapped == String) with a broader one (Wrapped: Collection) so that Array, Dictionary and Set also benefit our new isEmptyOrNil property:

    extension Optional where Wrapped: Collection {
    
        var isEmptyOrNil: Bool {
            return self?.isEmpty ?? true
        }
    
    }
    

    Usage with Strings:

    let optionalString: String? = nil
    print(optionalString.isEmptyOrNil) // prints: true
    
    let optionalString: String? = ""
    print(optionalString.isEmptyOrNil) // prints: true
    
    let optionalString: String? = "Hello"
    print(optionalString.isEmptyOrNil) // prints: false
    

    Usage with Arrays:

    let optionalArray: Array? = nil
    print(optionalArray.isEmptyOrNil) // prints: true
    
    let optionalArray: Array? = []
    print(optionalArray.isEmptyOrNil) // prints: true
    
    let optionalArray: Array? = [10, 22, 3]
    print(optionalArray.isEmptyOrNil) // prints: false
    

    Sources:

    • swiftbysundell.com - Extending optionals in Swift
    • objc.io - Swift Tip: Non-Empty Collections

提交回复
热议问题