I got stuck by the question in swift. Suppose I have one object, how to check whether it is from struct or class in swift.
A class in Swift is a reference type which can contain: It’s often described as a template definition of an object, like in the following Article instance definition: What is a struct in Swift? A struct in Swift is a value type which, just like classes, can contain:
A struct in Swift is a value type which, just like classes, can contain: It can also be seen as a template definition of an object, like in the following Article instance definition: What are the differences between a struct and a class?
In order to check if an object is of given type in Swift, you can use the type check operator is. Given an example class Item , you can check if the object is of its type like that: Same applies to built-in data types in Swift. For example, if you’d like to check if given object is a String or Int:
If field names do not match, you will get an error message: “The data couldn’t be read because it is missing..” Swift class or struct must conform to a Decodable or Codable protocol. In the code snippet above the UserResponseModel struct conforms to a Decodable protocol.
This approach has been working for me in Swift 3:
class TestClass { }
struct TestStruct { }
var mystery:Any
mystery = TestClass()
// Is mystery instance a class type?
print(type(of:mystery) is AnyClass ? "YES" : "NO") // prints: "YES"
mystery = TestStruct()
// Is mystery instance a class type?
print(type(of:mystery) is AnyClass ? "YES" : "NO") // prints: "NO"
Note that this approach tells you only if an instance is a class type or not. The fact that it's not a class doesn't necessarily mean it's a struct (could be an enum, closure, tuple, etc.) But for most purposes and contexts this is enough to know if you are dealing with a reference type or a value type, which is usually what is needed.
In Swift 3.0, you can call Mirror(reflecting:x).displayStyle
where x
is your value of interest. The result will be class
, struct
, enum
, dictionary
, set
... see the documentation https://developer.apple.com/reference/swift/mirror.displaystyle
Code sample:
struct SomeStruct {
var name: String
init(name: String) {
self.name = name
}
}
var astruct = SomeStruct(name:"myname")
Mirror(reflecting:astruct).displayStyle == .struct // will be true
Mirror(reflecting:astruct).displayStyle == .class; // will be false
class MyClass {
var name:String
init(name: String) {
self.name=name
}
}
var aclass = MyClass(name:"fsdfd")
Mirror(reflecting:aclass).displayStyle == .struct // will be false
Mirror(reflecting:aclass).displayStyle == .class // will be true
Of course, it would be best handled using a switch-case statement in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With