Check empty string in Swift?

前端 未结 15 1861
臣服心动
臣服心动 2020-11-28 03:51

In Objective C, one could do the following to check for strings:

if ([myString isEqualToString:@\"\"]) {
    NSLog(@\"m         


        
相关标签:
15条回答
  • 2020-11-28 04:38

    You can also use an optional extension so you don't have to worry about unwrapping or using == true:

    extension String {
        var isBlank: Bool {
            return self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
        }
    }
    extension Optional where Wrapped == String {
        var isBlank: Bool {
            if let unwrapped = self {
                return unwrapped.isBlank
            } else {
                return true
            }
        }
    }
    

    Note: when calling this on an optional, make sure not to use ? or else it will still require unwrapping.

    0 讨论(0)
  • 2020-11-28 04:38

    What about

    if let notEmptyString = optionalString where !notEmptyString.isEmpty {
        // do something with emptyString 
        NSLog("Non-empty string is %@", notEmptyString)
    } else {
        // empty or nil string
        NSLog("Empty or nil string")
    }
    
    0 讨论(0)
  • 2020-11-28 04:39
    if myString?.startIndex != myString?.endIndex {}
    
    0 讨论(0)
提交回复
热议问题