Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you retrieve the type of an object in Swift? [duplicate]

Tags:

swift

I cannot seem to find a function or method that returns the type of an object in Swift.

How does one retrieve the type or class of an object in Swift?

I tried using Obj-C classes which obviously did not work.

In python you have things like type or isinstance

In Javascript you have constructor

like image 815
Johnston Avatar asked Jun 04 '14 23:06

Johnston


People also ask

Which copy is used when a new instance type gets created and it keeps the values that are copied in the new instance?

As mentioned below, the value type instance keeps a unique copy of its data. So when using = syntax, it will pass all values to new object. Then the change in new object will not affect to old object.

What is NSCopying in Swift?

A protocol that objects adopt to provide functional copies of themselves.

What is Nsobject in iOS?

The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+


1 Answers

If you just need to check an object's type, you can use the type check operator, is, as in:

if myObject is UIView {
    // do something
}

If you want to try to call a method on the object but you aren't sure of the class, downcast the object to the type you need, like this:

if let myView = myObject as? UIView {
    myView.layer.backgroundColor = myColor
}
like image 109
Nate Cook Avatar answered Oct 11 '22 19:10

Nate Cook