Check string for nil & empty

后端 未结 23 1330
感动是毒
感动是毒 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:11

    If you are using Swift 2, here is an example my colleague came up with, which adds isNilOrEmpty property on optional Strings:

    protocol OptionalString {}
    extension String: OptionalString {}
    
    extension Optional where Wrapped: OptionalString {
        var isNilOrEmpty: Bool {
            return ((self as? String) ?? "").isEmpty
        }
    }
    

    You can then use isNilOrEmpty on the optional string itself

    func testNilOrEmpty() {
        let nilString:String? = nil
        XCTAssertTrue(nilString.isNilOrEmpty)
    
        let emptyString:String? = ""
        XCTAssertTrue(emptyString.isNilOrEmpty)
    
        let someText:String? = "lorem"
        XCTAssertFalse(someText.isNilOrEmpty)
    }
    

提交回复
热议问题