Swift에서 빈 문자열을 확인 하시겠습니까?
목표 C에서 문자열을 확인하기 위해 다음을 수행 할 수 있습니다.
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
Swift에서 빈 문자열을 어떻게 감지합니까?
빈 문자열을 감지하는 기능이 내장되어 있습니다 .isEmpty
.
if emptyString.isEmpty {
print("Nothing to see here")
}
Apple 시험판 문서 : "문자열 및 문자" .
문자열이 nil인지 비어 있는지 확인하는 간결한 방법은 다음과 같습니다.
var myString: String? = nil
if (myString ?? "").isEmpty {
print("String is nil or empty")
}
나는 내 답변을 완전히 다시 작성하고 있습니다 ( 다시 ). 이번에는 guard
성명서 의 팬이 되었고 일찍 돌아 왔기 때문 입니다. 훨씬 깨끗한 코드를 만듭니다.
비 선택적 문자열
길이가 0인지 확인하십시오.
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
return // or break, continue, throw
}
// myString is not empty (if this point is reached)
print(myString)
는 IF if
문을 통과, 당신은 안전하게이 비어 있지 않은 것을 알고 문자열을 사용할 수 있습니다. 비어 있으면 함수가 일찍 반환되고 중요한 후에 아무것도 반환되지 않습니다.
선택적 문자열
길이가 없거나 0인지 확인하십시오.
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)
이것은 선택 사항을 풀고 동시에 비어 있지 않은지 확인합니다. guard
명령문을 전달한 후 랩핑되지 않은 비어 있지 않은 문자열을 안전하게 사용할 수 있습니다.
Xcode 10.2 빠른 5에서
사용하다
var isEmpty: Bool { get }
예
let lang = "Swift 5"
if lang.isEmpty {
print("Empty string")
}
문자열이 비어 있는지 확인하는 방법은 다음과 같습니다. '공백'은 비어 있거나 공백 / 개행 문자 만 포함하는 문자열을 의미합니다.
struct MyString {
static func blank(text: String) -> Bool {
let trimmed = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return trimmed.isEmpty
}
}
사용하는 방법:
MyString.blank(" ") // true
선택적 확장을 사용하여 언 래핑 또는 사용에 대해 걱정할 필요가 없습니다 == 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
}
}
}
참고 : 옵션으로 이것을 호출 할 때 사용하지 마십시오. ?
그렇지 않으면 래핑 해제가 필요합니다.
부정 검사 및 길이를 동시에 수행하려면 Swift 2.0 및 iOS 9부터 사용할 수 있습니다.
if(yourString?.characters.count > 0){}
isEmpty will do as you think it will, if string == "", it'll return true. Some of the other answers point to a situation where you have an optional string.
PLEASE use Optional Chaining!!!!
If the string is not nil, isEmpty will be used, otherwise it will not.
Below, the optionalString will NOT be set because the string is nil
let optionalString: String? = nil
if optionalString?.isEmpty == true {
optionalString = "Lorem ipsum dolor sit amet"
}
Obviously you wouldn't use the above code. The gains come from JSON parsing or other such situations where you either have a value or not. This guarantees code will be run if there is a value.
For optional Strings how about:
if let string = string where !string.isEmpty
{
print(string)
}
Check check for only spaces and newlines characters in text
extension String
{
var isBlank:Bool {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
}
}
using
if text.isBlank
{
//text is blank do smth
}
if myString?.startIndex != myString?.endIndex {}
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")
}
참고URL : https://stackoverflow.com/questions/24133157/check-empty-string-in-swift
'Programing' 카테고리의 다른 글
IIS 7의 ASP MVC 결과 : HTTP 오류 403.14-금지 (0) | 2020.06.14 |
---|---|
Visual Studio 2013에서 단위 테스트를 찾지 못함 (0) | 2020.06.14 |
여러 줄에서 ghci로 함수를 정의하는 방법은 무엇입니까? (0) | 2020.06.14 |
두 개의 인라인 블록, 너비 50 % 요소가 두 번째 줄로 줄 바꿈 (0) | 2020.06.14 |
상대 경로 및 / 또는 파일 이름에서 절대 경로 확인 (0) | 2020.06.14 |