programing

Objective-C의 isEqualToString과 동등한 Swift는 무엇입니까?

cafebook 2023. 4. 23. 11:28
반응형

Objective-C의 isEqualToString과 동등한 Swift는 무엇입니까?

아래 코드를 실행하려고 합니다.

import UIKit

class LoginViewController: UIViewController {

@IBOutlet var username : UITextField = UITextField()
@IBOutlet var password : UITextField = UITextField()

@IBAction func loginButton(sender : AnyObject) {

    if username .isEqual("") || password.isEqual(""))
    {
        println("Sign in failed. Empty character")
    }
}

이전 코드는 Objective-C로 정상적으로 동작하고 있었습니다.

 if([[self.username text] isEqualToString: @""] ||
    [[self.password text] isEqualToString: @""] ) {

사용할 수 없을 것 같습니다.isEqualToString스위프트에서.

Swift를 사용하면 더 이상 동등성을 확인할 필요가 없습니다.isEqualToString

이제 를 사용할 수 있습니다.==

예:

let x = "hello"
let y = "hello"
let isEqual = (x == y)

현재 isequal은true.

대신 == 연산자 사용isEqual

문자열 비교

Swift는 문자열 값을 비교하는 세 가지 방법을 제공합니다. 문자열 등호화, 접두사 등호화 및 서픽스 등호화입니다.

문자열 등호도

두 String 값이 동일한 순서로 정확히 동일한 문자를 포함하는 경우 동일한 것으로 간주됩니다.

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

Swift(Strings 비교)에 대한 자세한 내용은 공식 문서를 참조하십시오.

에 추가합니다.@JJSaccolo응답: 커스텀을 생성할 수 있습니다.equals메서드는 다음과 같이 새로운 String 확장자로 지정됩니다.

extension String {
     func isEqualToString(find: String) -> Bool {
        return String(format: self) == find
    }
}

용도:

let a = "abc"
let b = "abc"

if a.isEqualToString(b) {
     println("Equals")
}

확실히 원래의 오퍼레이터==(Javascript에서처럼 동작)이 더 나을 수도 있지만, 저는isEqual메서드는 스트링을 비교할 수 있는 코드 명확성을 제공합니다.

그게 누군가에게 도움이 되었으면 좋겠는데

Swift에서 == 연산자는 Objective C의 isEqual: 메서드와 동일하므로(포인터를 비교하는 대신 isEqual 메서드를 호출하고 포인터가 동일한지 테스트하기 위한 새로운 === 메서드가 있습니다) 다음과 같이 쓸 수 있습니다.

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}

사실, 스위프트는 현을 물건처럼 취급하지 않고 가치관에 더 가깝도록 홍보하려는 것처럼 느껴집니다.단, 후드 스위프트에서 스트링을 오브젝트로 취급하지 않는 것은 아닙니다.여러분들도 스트링에서 메서드를 호출하여 그 속성을 사용할 수 있다는 것을 알고 계실 것입니다.

예를 들어 다음과 같습니다.

//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")


//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")

objectC에서는 변수를 통해 문자열 객체에 대한 참조를 호출 메서드 위에 전달할 수 있습니다.이것에 의해, 문자열이 순수한 오브젝트인 것이 거의 확립됩니다.

다음은 String을 객체로 보려고 할 때의 단점입니다.String 객체를 참조로 변수를 통과할 수 없습니다.스위프트는 항상 새 스트링 복사본을 전달합니다.따라서 일반적으로 문자열은 swift에서 값 유형으로 알려져 있습니다.실제로 두 문자열 리터럴은 동일하지 않습니다(===).두 개의 다른 복사본으로 취급됩니다.

let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")

보시다시피 우리는 현을 물건으로 생각하고 보다 가치 있게 취급하는 기존의 방식에서 벗어나기 시작했습니다.따라서 .isEqualToString은 문자열 객체의 ID 연산자로 취급되며 Swift에서는 동일한 문자열 객체를 2개 얻을 수 없기 때문에 유효하지 않습니다.이 값은 비교만 할 수 있습니다. 즉, 동등성(==)을 확인할 수 있습니다.

 let NotSoCuriousAnyMore = ("ca" == "ca")
 println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")

이것은 문자열 객체의 빠른 가변성을 보면 더욱 흥미로워집니다.하지만 그건 또 다른 질문이고, 또 다른 날입니다.아마 조사해야 할 것이 있기 때문에 매우 흥미롭습니다. :) 혼란이 해소되기를 바랍니다.건배!

아래 코드를 사용하고 있는 UITextField 텍스트의 비교에 대해서는, 에러가 발견되면 알려 주세요.

if(txtUsername.text.isEmpty || txtPassword.text.isEmpty)
{
    //Do some stuff
}
else if(txtUsername.text == "****" && txtPassword.text == "****")
{
    //Do some stuff
}

더 스위프트에서isEmpty이 함수는 문자열이 비어 있는지 확인합니다.

 if username.isEmpty || password.isEmpty {
      println("Sign in failed. Empty character")
 }

가지 의 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.== 수 .-isEqualToString:【Swift】【Objective-C】【객관】

예를 들어 보겠습니다.

let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)

composed.utf16.count // 1
decomposed.utf16.count // 2

let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString

decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not

NSString는 UTF-16 코드 유닛의 시퀀스로 표시됩니다(대략 UTF-16(고정폭) 코드 유닛의 배열로 읽힙니다). Swift는String는 "문자"의 개념적 시퀀스이며, 여기서 "문자"는 확장된 그래핀 클러스터를 추상화하는 것입니다(문자 = 유니코드 코드 포인트의 양을 읽습니다. 일반적으로 사용자가 문자로 보고 텍스트 입력 커서가 이리저리 움직입니다).

하다쓸 것이 많지만, 여기서는 "캐노컬 등가성"이라는 것에 관심이 있습니다.유니코드 코드 포인트를 사용하면, 시각적으로 같은 「문자」를 복수의 방법으로 부호화할 수 있습니다.를 들어는 미리 된 "A"로 나타낼 수"A"는 "A"로 됩니다).composed.utf16 ★★★★★★★★★★★★★★★★★」decomposed.utf16길이가 달랐습니다).그것에 대해 읽어볼 수 있는 좋은 은 이 훌륭한 기사이다.

-[NSString isEqualToString:] 매뉴얼에 따르면는 NSStrings 코드 유닛을 코드 유닛별로 비교하기 때문에 다음과 같습니다.

[Á] != [A, ◌́]

의 스트링== 는 표준 동등성으로 문자를 비교합니다.

[ [Á] ] == [ [A, ◌́] ]

현악기★★★★★★★★★★★★★★★★★★.-[NSString isEqualToString:]Swift String == ((와와와와와 swift swift swift swift swift swift swift swift swift. ViewsString UTF-16을 비교함으로써 할 수 .

decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same

, 른, 다, 다, 다, 습, 습, 습, 습, also, also, also, also, also, also,NSString == NSString ★★★★★★★★★★★★★★★★★」String == String★★★★★★★★★★★★★★★★★★★★★★★.NSString ==는, 유닛의및 유닛의 서 isEqual UTF-16은 UTF-16으로 되어 있습니다.String ==는 표준합니다.

decomposed == composed // true, Strings are equal
decomposed as NSString == composed as NSString // false, UTF-16 code units are not the same

그리고 전체 예는 다음과 같습니다.

let composed = "Ö" // U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS
let decomposed = composed.decomposedStringWithCanonicalMapping // (U+004F LATIN CAPITAL LETTER O) + (U+0308 COMBINING DIAERESIS)

composed.utf16.count // 1
decomposed.utf16.count // 2

let composedNSString = composed as NSString
let decomposedNSString = decomposed as NSString

decomposed == composed // true, Strings are equal
decomposedNSString == composedNSString // false, NSStrings are not

decomposed.utf16.elementsEqual(composed.utf16) // false, UTF-16 code units are not the same
decomposedNSString == composedNSString // false, UTF-16 code units are not the same
decomposedNSString.isEqual(to: composedNSString as String) // false, UTF-16 code units are not the same

언급URL : https://stackoverflow.com/questions/24096708/what-is-the-swift-equivalent-of-isequaltostring-in-objective-c

반응형