Programing

nil & empty의 문자열 확인

lottogame 2020. 7. 22. 20:51
반응형

nil & empty의 문자열 확인


에 대한 문자열을 확인 할 수있는 방법이 있나요 nil""스위프트의는? Rails에서는 blank()확인할 수 있습니다 .

나는 현재 이것을 가지고 있지만 과잉 것 같습니다 :

    if stringA? != nil {
        if !stringA!.isEmpty {
            ...blah blah
        }
    }

선택적 문자열을 다루는 경우 다음과 같이 작동합니다.

(string ?? "").isEmpty

??는 비 전무의 경우 전무 병합 연산자 그렇지 않으면 오른쪽을 반환 왼쪽을 반환합니다.

다음과 같이 사용하여 기본값을 반환 할 수도 있습니다.

(string ?? "").isEmpty ? "Default" : string!

if-let-where 절을 사용할 수 있습니다.

스위프트 3 :

if let string = string, !string.isEmpty {
    /* string is not blank */
}

스위프트 2 :

if let string = string where !string.isEmpty {
    /* string is not blank */
}

Swift 2를 사용하는 경우 다음은 내 동료가 제시 한 예제이며 선택적 문자열에 isNilOrEmpty 속성을 추가합니다.

protocol OptionalString {}
extension String: OptionalString {}

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

그런 다음 선택적 문자열 자체에서 isNilOrEmpty를 사용할 수 있습니다

func testNilOrEmpty() {
    let nilString:String? = nil
    XCTAssertTrue(nilString.isNilOrEmpty)

    let emptyString:String? = ""
    XCTAssertTrue(emptyString.isNilOrEmpty)

    let someText:String? = "lorem"
    XCTAssertFalse(someText.isNilOrEmpty)
}

guard진술 사용

나는 guard진술 에 대해 배우기 전에 잠시 동안 Swift를 사용하고있었습니다 . 지금 나는 큰 팬입니다. if명령문 과 유사하게 사용 되지만 조기 리턴을 허용 하고 일반적으로 훨씬 깨끗한 코드를 만듭니다.

문자열이 0이 아니거나 비어 있지 않은지 확인할 때 guard를 사용하려면 다음을 수행하십시오.

let myOptionalString: String? = nil

guard let myString = myOptionalString, !myString.isEmpty else {
    print("String is nil or empty.")
    return // or break, continue, throw
}

/// myString is neither nil nor empty (if this point is reached)
print(myString)

옵션 문자열을 풀고 한 번에 비어 있지 않은지 확인합니다. 그것이 nil (또는 비어 있다면)이면 즉시 함수 (또는 루프)에서 돌아가고 그 이후의 모든 것이 무시됩니다. 그러나 guard 문이 통과하면 래핑되지 않은 문자열을 안전하게 사용할 수 있습니다.

또한보십시오


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")
}

Swift 5를 사용하면 선택적 문자열에 값이 없거나 비어있는 경우를 반환하는 부울 속성을 사용하여 유형에 대한 Optional확장을 구현할 수 있습니다 String.

extension Optional where Wrapped == String {

    var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }

}

그러나 protocol을 준수하여 속성을 String구현 isEmpty합니다 Collection. 그러므로 우리는 이전 코드의 일반적인 제약 (대체 할 수있는 Wrapped == String폭 넓은 하나 (과) Wrapped: Collection) 그래서 Array, Dictionary그리고 Set또한 우리의 새로운 혜택 isNilOrEmpty속성을 :

extension Optional where Wrapped: Collection {

    var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }

}

Strings를 사용한 사용법 :

let optionalString: String? = nil
print(optionalString.isNilOrEmpty) // prints: true
let optionalString: String? = ""
print(optionalString.isNilOrEmpty) // prints: true
let optionalString: String? = "Hello"
print(optionalString.isNilOrEmpty) // prints: false

Arrays를 사용한 사용법 :

let optionalArray: Array<Int>? = nil
print(optionalArray.isNilOrEmpty) // prints: true
let optionalArray: Array<Int>? = []
print(optionalArray.isNilOrEmpty) // prints: true
let optionalArray: Array<Int>? = [10, 22, 3]
print(optionalArray.isNilOrEmpty) // prints: false

출처 :


나는이 질문에 대한 많은 답변이 있다는 것을 알고 있지만 UITextField, 데이터 를 확인하는 데 (이것은 내 의견으로는) 편리한 것 같지 않습니다.이를 사용하는 가장 일반적인 경우 중 하나입니다.

extension Optional where Wrapped == String {
    var isNilOrEmpty: Bool {
        return self?.trimmingCharacters(in: .whitespaces).isEmpty ?? true
    }
}

당신은 그냥 사용할 수 있습니다

textField.text.isNilOrEmpty

You can also skip the .trimmingCharacters(in:.whitespaces) if you don't consider whitespaces as an empty string or use it for more complex input tests like

var isValidInput: Bool {
    return !isNilOrEmpty && self!.trimmingCharacters(in: .whitespaces).characters.count >= MIN_CHARS
}

I would recommend.

if stringA.map(isEmpty) == false {
    println("blah blah")
}

map applies the function argument if the optional is .Some.
The playground capture also shows another possibility with the new Swift 1.2 if let optional binding.

enter image description here


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
}

SWIFT 3

extension Optional where Wrapped == String {

    /// Checks to see whether the optional string is nil or empty ("")
    public var isNilOrEmpty: Bool {
        if let text = self, !text.isEmpty { return false }
        return true
    }
}

Use like this on optional string:

if myString.isNilOrEmpty { print("Crap, how'd this happen?") } 

Swift 3 For check Empty String best way

if !string.isEmpty{

// do stuff

}

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")
}

Swift 3 solution Use the optional unwrapped value and check against the boolean.

if (string?.isempty == true) {
    // Perform action
}

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!")
}

Swift 3 This works well to check if the string is really empty. Because isEmpty returns true when there's a whitespace.

extension String {
    func isEmptyAndContainsNoWhitespace() -> Bool {
        guard self.isEmpty, self.trimmingCharacters(in: .whitespaces).isEmpty
            else {
               return false
        }
        return true
    }
}

Examples:

let myString = "My String"
myString.isEmptyAndContainsNoWhitespace() // returns false

let myString = ""
myString.isEmptyAndContainsNoWhitespace() // returns true

let myString = " "
myString.isEmptyAndContainsNoWhitespace() // returns false

You should do something like this:
if !(string?.isEmpty ?? true) { //Not nil nor empty }

Nil coalescing operator checks if the optional is not nil, in case it is not nil it then checks its property, in this case isEmpty. Because this optional can be nil you provide a default value which will be used when your optional is nil.


This is a general solution for all types that conform to the Collection protocol, which includes String:

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        return self?.isEmpty ?? true
    }
}

When dealing with passing values from local db to server and vice versa, I was having too much trouble with ?'s and !'s and what not.

So I made a Swift3.0 utility to handle null cases and i can almost totally avoid ?'s and !'s in the code.

func str(_ string: String?) -> String {
    return (string != nil ? string! : "")
}

Ex:-

Before :

    let myDictionary: [String: String] = 
                      ["title": (dbObject?.title != nil ? dbObject?.title! : "")]

After :

    let myDictionary: [String: String] = 
                        ["title": str(dbObject.title)]

and when its required to check for a valid string,

    if !str(dbObject.title).isEmpty {
        //do stuff
    }

This saved me having to go through the trouble of adding and removing numerous ?'s and !'s after writing code that reasonably make sense.


Use the ternary operator (also known as the conditional operator, C++ forever!):

if stringA != nil ? stringA!.isEmpty == false : false { /* ... */ }

The stringA! force-unwrapping happens only when stringA != nil, so it is safe. The == false verbosity is somewhat more readable than yet another exclamation mark in !(stringA!.isEmpty).

I personally prefer a slightly different form:

if stringA == nil ? false : stringA!.isEmpty == false { /* ... */ }

In the statement above, it is immediately very clear that the entire if block does not execute when a variable is nil.


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.


Using isEmpty

"Hello".isEmpty  // false
"".isEmpty       // true

Using allSatisfy

extension String {
  var isBlank: Bool {
    return allSatisfy({ $0.isWhitespace })
  }
}

"Hello".isBlank        // false
"".isBlank             // true

Using optional String

extension Optional where Wrapped == String {
  var isBlank: Bool {
    return self?.isBlank ?? true
  }
}

var title: String? = nil
title.isBlank            // true
title = ""               
title.isBlank            // true

Reference : https://useyourloaf.com/blog/empty-strings-in-swift/


you can use this func

 class func stringIsNilOrEmpty(aString: String) -> Bool { return (aString).isEmpty }

참고URL : https://stackoverflow.com/questions/29381994/check-string-for-nil-empty

반응형