Note: there is a similar question posted for objective c over here, but I want to achieve it in swift.
I have a class declared in swift like this:
import UIKit
class EachDayCell : UITableViewCell
{
@IBOutlet var dateDisplayLabel : UITextField
@IBOutlet var nameDisplayLabel : UITextField
@IBAction func goToPendingItems(sender : AnyObject) {
}
@IBAction func showDateSelectionPicker(sender : AnyObject) {
}
init(style: UITableViewCellStyle, reuseIdentifier: String!)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
}
Now I want to get an array in swift enlisting: dateDisplayLabel, nameDisplayLabel.
How can I achieve this?
Here is another version.I think this is much simple and pure.
Swift 2.0
Swift 1.2
I converted bolivia's code to Swift 4. This function takes in an NSObject and returns a dictionary of the object's keys and the type of that key.
Note that the types are kind of ugly. For primitive properties the engine returns a one letter identifier (like
B
for bool,i
for int, etc) but for Obj-C types it returns things like@"NSString"
. Seeing as this is really just a debugging function for me I didn't mind. If you don't want to mess with the dictionary you can just uncomment theprint
line and get it dumped to the console.String(cString:cAttr)
also contains a lot of useful info including if the property is mutable, it's reference style, and much more. For more info on this here's Apple's documentation.Using
Mirror
Here's a pure Swift solution with some limitations:
Limitations:
Will not return computed properties, i.e.:
If
self
is an instance of a class (vs., say, a struct), this doesn't report its superclass's properties, i.e.:You could work around this using
superclassMirror()
depending on your desired behavior.Using
class_copyPropertyList
If you're using Objective-C objects you can use this approach:
The output to the console if
classToInspect
isNSURL
:This won't work in a playground. Just replace
NSURL
withEachDayCell
(or reuse the same logic as an extension) and it should work.Swift 3.1