Check string for nil & empty

后端 未结 23 1237
感动是毒
感动是毒 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<Int>? = nil
    print(optionalArray.isEmptyOrNil) // prints: true
    
    let optionalArray: Array<Int>? = []
    print(optionalArray.isEmptyOrNil) // prints: true
    
    let optionalArray: Array<Int>? = [10, 22, 3]
    print(optionalArray.isEmptyOrNil) // prints: false
    

    Sources:

    • swiftbysundell.com - Extending optionals in Swift
    • objc.io - Swift Tip: Non-Empty Collections
    0 讨论(0)
  • 2020-12-07 11:13

    Create a String class extension:

    extension String
    {   //  returns false if passed string is nil or empty
        static func isNilOrEmpty(_ string:String?) -> Bool
        {   if  string == nil                   { return true }
            return string!.isEmpty
        }
    }// extension: String
    

    Notice this will return TRUE if the string contains one or more blanks. To treat blank string as "empty", use...

    return string!.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
    

    ... instead. This requires Foundation.

    Use it thus...

    if String.isNilOrEmpty("hello world") == true 
    {   print("it's a string!")
    }
    
    0 讨论(0)
  • 2020-12-07 11:14

    helpful when getting value from UITextField and checking for nil & empty string

    @IBOutlet weak var myTextField: UITextField!
    

    Heres your function (when you tap on a button) that gets string from UITextField and does some other stuff

    @IBAction func getStringFrom_myTextField(_ sender: Any) {
    
    guard let string = myTextField.text, !(myTextField.text?.isEmpty)!  else { return }
        //use "string" to do your stuff.
    }
    

    This will take care of nil value as well as empty string.

    It worked perfectly well for me.

    0 讨论(0)
  • 2020-12-07 11:15
    var str: String? = nil
    
    if str?.isEmpty ?? true {
        print("str is nil or empty")
    }
    
    str = ""
    
    if str?.isEmpty ?? true {
        print("str is nil or empty")
    }
    
    0 讨论(0)
  • 2020-12-07 11:16

    If you want to access the string as a non-optional, you should use Ryan's Answer, but if you only care about the non-emptiness of the string, my preferred shorthand for this is

    if stringA?.isEmpty == false {
        ...blah blah
    }
    

    Since == works fine with optional booleans, I think this leaves the code readable without obscuring the original intention.

    If you want to check the opposite: if the string is nil or "", I prefer to check both cases explicitly to show the correct intention:

    if stringA == nil || stringA?.isEmpty == true {
        ...blah blah
    }
    
    0 讨论(0)
  • 2020-12-07 11:16

    You can create your own custom function, if that is something you expect to do a lot.

    func isBlank (optionalString :String?) -> Bool {
        if let string = optionalString {
            return string.isEmpty
        } else {
            return true
        }
    }
    
    
    
    var optionalString :String? = nil
    
    if isBlank(optionalString) {
        println("here")
    }
    else {
        println("there")
    }
    
    0 讨论(0)
提交回复
热议问题