简体   繁体   中英

XCode Swift: Adding new class variables to existing Class

I am looking for a way to extend an existing class with new variables without creating my own new class, eg add an NSIndexPath to UITableViewCell to be able to access row or section without the use of tags.

I known i can add new functions with an extension

extension UITableViewCell {
    // i can do this
    func myExtendedFunction() {}
    // but this is not possible
    var indexPath:NSIndexPath
}

Is there a way to do this, or do i always have to build my own classes?

You need to subclass to add properties to a class.

There are workarounds relying on the objc runtime to allow you to associate objects with each other, but these should not be used in the typical case (they are typically more complex than subclassing, they make the relationships between objects non obvious, and have their own limitations).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM