programing

Swift에서 개체가 지정된 유형인지 확인하는 중

telebox 2023. 4. 12. 22:14
반응형

Swift에서 개체가 지정된 유형인지 확인하는 중

이 어레이는 다음과 같이 구성되어 있습니다.AnyObject반복하여 어레이 인스턴스의 모든 요소를 찾습니다.

Swift에서 오브젝트가 특정 타입인지 어떻게 확인할 수 있습니까?

특정 유형에 대해 검사하려면 다음을 수행합니다.

if let stringArray = obj as? [String] {
    // obj is a string array. Do something with stringArray
}
else {
    // obj is not a string array
}

"하면 "as!"를 하면 런타임 합니다.obj[String]

let stringArray = obj as! [String]

한 번에 1개의 요소를 체크할 수도 있습니다.

let items : [Any] = ["Hello", "World"]
for obj in items {
   if let str = obj as? String {
      // obj is a String. Do something with str
   }
   else {
      // obj is not a String
   }
}

Swift 2.2 - 5에서는 다음 작업을 수행할 수 있습니다.

if object is String
{
}

다음으로 어레이를 필터링합니다.

let filteredArray = originalArray.filter({ $0 is Array })

확인할 유형이 여러 개 있는 경우:

    switch object
    {
    case is String:
        ...

    case is OtherClass:
        ...

    default:
        ...
    }

개체가 특정 유형의 하위 유형인지 여부만 알고 싶다면 다음과 같은 간단한 방법이 있습니다.

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

func area (shape: Shape) -> Double {
  if shape is Circle { ... }
  else if shape is Rectangle { ... }
}

유형 검사 연산자(is)를 사용하여 인스턴스가 특정 하위 클래스 유형인지 확인합니다.type check 연산자는 인스턴스가 해당 서브클래스 유형이면 true를 반환하고 그렇지 않으면 false를 반환합니다."출처: Apple Inc.에서 발췌.'스위트 프로그래밍 언어' 아이북스

위에서는 '특정 서브클래스 유형의'이라는 문구가 중요합니다.「 」의 is Circle ★★★★★★★★★★★★★★★★★」is Rectangle그입니다.shape라고 Shape)Circle ★★★★★★★★★★★★★★★★★」Rectangle를 참조해 주세요.

타입을 경우 는 ' class'가 됩니다.Any하다

 21> func test (obj:Any) -> String {
 22.     if obj is Int { return "Int" }
 23.     else if obj is String { return "String" }
 24.     else { return "Any" }
 25. } 
 ...  
 30> test (1)
$R16: String = "Int"
 31> test ("abc")
$R17: String = "String"
 32> test (nil)
$R18: String = "Any"

swift4의 경우:

if obj is MyClass{
    // then object type is MyClass Type
}

다음 두 가지 방법이 있습니다.

if let thisShape = aShape as? Square 

또는 다음 중 하나를 선택합니다.

aShape.isKindOfClass(Square)

다음으로 상세한 예를 제시하겠습니다.

class Shape { }
class Square: Shape { } 
class Circle: Shape { }

var aShape = Shape()
aShape = Square()

if let thisShape = aShape as? Square {
    println("Its a square")
} else {
    println("Its not a square")
}

if aShape.isKindOfClass(Square) {
    println("Its a square")
} else {
    println("Its not a square")
}

편집: 지금 바로 3개:

let myShape = Shape()
if myShape is Shape {
    print("yes it is")
}

drawTriangle이 UIView의 인스턴스라고 가정합니다.drawTriangle이 UITableView 유형인지 확인하려면:

Swift 3에서는

if drawTriangle is UITableView{
    // in deed drawTriangle is UIView
    // do something here...
} else{
    // do something here...
}

또한 사용자가 정의한 클래스에도 사용할 수 있습니다.이를 사용하여 보기의 하위 보기를 확인할 수 있습니다.

다만, 인정된 답변과 그 외의 일부에 근거해, 완성도를 높이기 위해서입니다.

let items : [Any] = ["Hello", "World", 1]

for obj in items where obj is String {
   // obj is a String. Do something with str
}

(이렇게, 이렇게)도할 수 있어요.compactMap ,, 치, 치, 치, which, which, which, which, which, which, which, which, which, which, which, which, which filter( ) :

items.compactMap { $0 as? String }.forEach{ /* do something with $0 */ ) }

음음음음음 using using using를 한 버전.switch:

for obj in items {
    switch (obj) {
        case is Int:
           // it's an integer
        case let stringObj as String:
           // you can do something with stringObj which is a String
        default:
           print("\(type(of: obj))") // get the type
    }
}

하기 위해서 ( 배열인지, 배열인지, 배열인지, 배열인지) 확인할 수 .[String]

let items : [Any] = ["Hello", "World", 1, ["Hello", "World", "of", "Arrays"]]

for obj in items {
  if let stringArray = obj as? [String] {
    print("\(stringArray)")
  }
}

또는 보다 일반적으로(다른 질문 답변 참조):

for obj in items {
  if obj is [Any] {
    print("is [Any]")
  }

  if obj is [AnyObject] {
    print("is [AnyObject]")
  }

  if obj is NSArray {
    print("is NSArray")
  }
}

이 태스크용으로 특별히 내장된 기능을 사용하면 어떨까요?

let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)

Result: "Array<Any>"

이 점에 주의:

var string = "Hello" as NSString
var obj1:AnyObject = string
var obj2:NSObject = string

print(obj1 is NSString)
print(obj2 is NSString)
print(obj1 is String)
print(obj2 is String) 

마지막 4행 모두 true를 반환한다.이것은, 다음과 같이 입력했을 경우,

var r1:CGRect = CGRect()
print(r1 is String)

...물론 "false"로 출력되지만 CGRect에서 String으로의 캐스트에 장애가 발생한다는 경고가 표시됩니다.따라서 일부 유형은 브리징되며, is 키워드는 암묵적인 캐스트를 호출합니다.

다음 중 하나를 사용하는 것이 좋습니다.

myObject.isKind(of: MyClass.self)) 
myObject.isMember(of: MyClass.self))

as?항상 기대했던 결과를 얻을 수 있는 것은 아닙니다.왜냐하면as는, 데이터 타입이 특정의 종류인지 아닌지를 테스트하지 않습니다.단, 데이터 타입이 특정의 종류로 변환 또는 표현될 수 있는 경우에만 테스트합니다.

다음 코드를 예로 들 수 있습니다.

func handleError ( error: Error ) {
    if let nsError = error as? NSError {

에 준거하는 모든 데이터 타입Error프로토콜은 로 변환할 수 있습니다.NSError이 작업은 항상 성공합니다.그렇다고 해서error사실 a다NSError오브젝트 또는 서브클래스를 지정합니다.

올바른 유형 검사는 다음과 같습니다.

func handleError ( error: Error ) {
    if type(of: error) == NSError.self {

다만, 이것은 정확한 타입만을 체크합니다.의 서브클래스도 포함할 경우NSError, 다음을 사용합니다.

func handleError ( error: Error ) {
    if error is NSError.Type {

이 함수를 사용하여 다음과 같이 호출할 수 있습니다.

func printInfo(_ value: Any) {
    let t = type(of: value)
    print("'\(value)' of type '\(t)'")
}

예를 들어 다음과 같습니다.printInfo(data)

'데이터' 유형의 '125바이트'

myObject as? String돌아온다nil한다면myObject이 아니다String. 그렇지 않으면 A가 반환됩니다.String?를 사용하여 문자열 자체에 액세스할 수 있습니다.myObject!또는 로 캐스팅합니다.myObject! as String안전하게.

정의되지 않은 값(someVariable...을 그대로 사용)으로 인해 경고를 받지 않고 클래스를 체크하는 경우 let 항목을 부울로 바꿀 수 있습니다.

if (yourObject as? ClassToCompareWith) != nil {
   // do what you have to do
}
else {
   // do something else
}

Xcode는 let way를 사용하고 정의된 값을 사용하지 않을 때 이것을 제안했습니다.

왜 이런 걸 쓰지 않는 거죠?

fileprivate enum types {
    case typeString
    case typeInt
    case typeDouble
    case typeUnknown
}

fileprivate func typeOfAny(variable: Any) -> types {
    if variable is String {return types.typeString}
    if variable is Int {return types.typeInt}
    if variable is Double {return types.typeDouble}
    return types.typeUnknown
}

Swift 3에서.

Swift 4.2의 경우 isKind 함수를 사용합니다.

isKind(of:) 수신기가 지정된 클래스의 인스턴스인지 또는 해당 클래스에서 상속된 클래스의 인스턴스인지를 나타내는 부울 값을 반환합니다.

  let items : [AnyObject] = ["A", "B" , ... ]
  for obj in items {
    if(obj.isKind(of: NSString.self)){
      print("String")
    }
  }

자세한 내용은 https://developer.apple.com/documentation/objectivec/nsobjectprotocol/1418511-iskind를 참조하십시오.

스위프트 3:

class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}

if aShape.isKind(of: Circle.self) {
}

스위프트 5.2 & Xcode 버전: 11.3.1 (11C504)

데이터 타입을 체크하기 위한 솔루션을 다음에 나타냅니다.

 if let typeCheck = myResult as? [String : Any] {
        print("It's Dictionary.")
    } else { 
        print("It's not Dictionary.") 
    }

도움이 되길 바랍니다.

다음과 같은 응답이 있는 경우:

{
  "registeration_method": "email",
  "is_stucked": true,
  "individual": {
    "id": 24099,
    "first_name": "ahmad",
    "last_name": "zozoz",
    "email": null,
    "mobile_number": null,
    "confirmed": false,
    "avatar": "http://abc-abc-xyz.amazonaws.com/images/placeholder-profile.png",
    "doctor_request_status": 0
  },
  "max_number_of_confirmation_trials": 4,
  "max_number_of_invalid_confirmation_trials": 12
}

가치를 확인하고 싶다is_stuckedAnyObject로 읽힙니다.이것만 하면 됩니다.

if let isStucked = response["is_stucked"] as? Bool{
  if isStucked{
      print("is Stucked")
  }
  else{
      print("Not Stucked")
 }
}

서버에서 응답에 사전 또는 단일 사전 배열을 가져올지 모를 경우 결과에 배열이 포함되어 있는지 확인해야 합니다.
내 경우엔 한 번을 제외하고는 항상 사전들을 받는다.그래서 나는 그것을 처리하기 위해 swift 3에 아래의 코드를 사용했습니다.

if let str = strDict["item"] as? Array<Any>

여기서요?Array는 취득한 값이 (사전 항목의) 배열인지 여부를 확인합니다.그렇지 않으면 배열 내에 보관되지 않은 단일 사전 항목인 경우 처리할 수 있습니다.

let originalArray : [Any?] = ["Hello", "World", 111, 2, nil, 3.34]
let strings = originalArray.compactMap({ $0 as? String })

print(strings)
//printed: ["Hello", "World"]

언급URL : https://stackoverflow.com/questions/24091882/checking-if-an-object-is-a-given-type-in-swift

반응형