How to check if a string is blank (empty, nil, or contains only whitespace) in Swift

1 Answer

0 votes
import Foundation

func isBlankOrEmpty(_ str: String?) -> Bool {
    // Check for nil or empty string
    guard let str = str, !str.isEmpty else {
        return true
    }

    // Check if the string contains only whitespace
    return str.allSatisfy { $0.isWhitespace }
}

let testCases: [String?] = [nil, "", "   ", "abc"]

for (index, test) in testCases.enumerated() {
    print("Test\(index + 1): \(isBlankOrEmpty(test))")
}



/*
run:

Test1: true
Test2: true
Test3: true
Test4: false

*/

 



answered Jun 8 by avibootz
...