Check empty string in Swift?

前端 未结 15 1975
臣服心动
臣服心动 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.

提交回复
热议问题