How to check two instances are the same class/type in swift
I feel necessary to quote from the Swift Programming Language documentation first of all:
Classes have additional capabilities that structures do not:
- Type casting enables you to check and interpret the type of a class instance at runtime.
According to this, it may be helpful for someone in the future:
func areTheySiblings(class1: AnyObject!, class2: AnyObject!) -> Bool {
return object_getClassName(class1) == object_getClassName(class2)
}
and the tests:
let myArray1: Array<AnyObject> = Array()
let myArray2: Array<Int> = Array()
let myDictionary: Dictionary<String, Int> = Dictionary()
let myString: String = String()
let arrayAndArray: Bool = self.areTheySiblings(myArray1, class2: myArray2) // true
let arrayAndString: Bool = self.areTheySiblings(myArray1, class2: myString) // false
let arrayAndDictionary: Bool = self.areTheySiblings(myArray1, class2: myDictionary) // false
UPDATE
you also can overload a new operator for doing such a thing, like e.g. this:
infix operator >!<
func >!< (object1: AnyObject!, object2: AnyObject!) -> Bool {
return (object_getClassName(object1) == object_getClassName(object2))
}
and the results:
println("Array vs Array: \(myArray1 >!< myArray2)") // true
println("Array vs. String: \(myArray1 >!< myString)") // false
println("Array vs. Dictionary: \(myArray1 >!< myDictionary)") // false
UPDATE#2
you can also use it for your own new Swift classes, like e.g. those:
class A { }
class B { }
let a1 = A(), a2 = A(), b = B()
println("a1 vs. a2: \(a1 >!< a2)") // true
println("a1 vs. b: \(a1 >!< b)") // false
Swift - check if two objects are of same type or superclass-type
One way could be to try generics like this
func isObject<P>(_ object: Any, ofType other: P) -> Bool {
object is P
}
isObject(myObject, ofType: myOtherObject) //true
isObject(mySubclassedObject, ofType: myObject) //true
isObject(myObject, ofType: mySubclassedObject) //false
Swift: checking 2 object from same class have different values?
I think you're looking for something like this pretty much:
import Foundation
class MyClass {
var someString: String = ""
var someInt: Int = 0
}
let a = MyClass()
a.someString = "A object"
a.someInt = 1
let b = MyClass()
b.someString = "B object"
b.someInt = 2
func compare<T: MyClass>(_ instance: T, with instance2: T) -> [String: AnyHashable] {
let sourceMirror = Mirror(reflecting: instance)
let targetMirror = Mirror(reflecting: instance2)
var output = [String: AnyHashable]()
for sourceChild in sourceMirror.children {
guard let label = sourceChild.label else { continue }
guard let targetChild = (targetMirror.children.first { $0.label! == label }) else {
fatalError("Failed to find target child, since types are same this fatal error should not be fired")
}
guard
let firstValue = sourceChild.value as? AnyHashable,
let secondValue = targetChild.value as? AnyHashable
else {
continue
}
guard firstValue != secondValue else { continue }
output[label] = secondValue
}
return output
}
for result in compare(a, with: b) {
print("label: \(result.key), value: \(result.value)")
}
The downside of this method is all of your fields must be conforming to Hashable protocol if you want to see the difference between these.
The output is:
label: someInt, value: 2
label: someString, value: B object
Compare two instances of an object in Swift
Indicate that your class conforms to the Equatable protocol, and then implement the == operator.
Something like this:
class PLClient: Equatable
{
var name = String()
var id = String()
var email = String()
var mobile = String()
var companyId = String()
var companyName = String()
//The rest of your class code goes here
public static func ==(lhs: PLClient, rhs: PLClient) -> Bool{
return
lhs.name == rhs.name &&
lhs.id == rhs.id &&
lhs.email == rhs.email &&
lhs.mobile == rhs.mobile &&
lhs.companyId == rhs.companyId &&
lhs.companyName == rhs.companyName
}
}
Better way to check the instance is kind from list of classes?
If I think about it logically, it would make a lot more sense to define a superclass / protocol for them, something like this:
class MyClassNumber { }
class MyClassOne: MyClassNumber { }
class MyClassTwo: MyClassNumber { }
class MyClassLetter { }
let one = MyClassOne()
let two = MyClassTwo()
let letter = MyClassLetter()
if one is MyClassNumber {
// TRUE
}
if two is MyClassNumber {
// TRUE
}
if letter is MyClassLetter {
// FALSE
}
Don't see any use case for yours
How to check if two objects have the same class in Kotlin?
You can get the type of an object with ::class
, and compare those:
val sameClass = obj1::class == obj2::class
More specifically, this section of the above documentation describes that ::class
on an object gives you exactly what you want, the exact class of the instance you're calling it on.
Swift Check if Two Objects Conforming to a Protocol Are Referentially The Same
You should try to upcast the delegate
and then check for equality:
func something() {
if item.delegate as? Container !== self {
print("hi")
}
}
Full working code example
protocol ContainerDelegate {}
protocol FileProtocol {
var delegate: ContainerDelegate? { get set }
}
class StaticFile: NSObject, FileProtocol {
var delegate: ContainerDelegate?
}
class Container: NSObject, ContainerDelegate {
var item: FileProtocol
func something() {
if item.delegate as? Container !== self {
print("hi")
}
}
override init() {
item = StaticFile()
}
}
let c = Container()
let c2 = Container()
c.item.delegate = c2
c.something() // hi gets printed
c.item.delegate = c
c.something() // hi does **not** get printed
Related Topics
Is Swiftui Backwards-Compatible With iOS 12.X and Older
How String Comparison Happens in Swift
May I Create an Instance of a Structure Using a Simple Int
How to Set Collection View's Cell Size via the Auto Layout
Download File from Server Using Swift
Swift Setter Causing Exc_Bad_Access
How to Properly Use Queryorderedbyvalue
Uitableview Load More When Scrolling to Bottom
Replacing Calayer and Cabasicanimation with Skscene and Skactions
How to Use the Appropriate Color Class For the Current Platform
Any Way to Iterate a Tuple in Swift
Swift Generics: Requiring Addition and Multiplication Abilities of a Type
Swift Semantics Regarding Dictionary Access
Remove Default Padding from List in Swiftui
Swift Custom Context Menu Previewprovider Can Not Click Any View Inside(Using Tapgesture)