Some small steps to begin wrapping my head around Swift. I've basically ported an old class that simply finds the matching icon for a name and return the appropriate UIImage. The Swift part of things seems to be up and running, and looks (almost) like this:
@objc class ImageHandler{ func iconForData(data: MyData) -> UIImage{ let imagesAndNames = [ "1": "tree.png", "2": "car.png", "3": "house.png", "7": "boat.png", ] var imageName: String? = imagesAndNames[data.imageName] if !imageName{ imageName = "placeholder.png" } let icon = UIImage(named: imageName) return icon } }
There are no warnings on the above. My old Objective-C class is however asking for an alloc method on the swift class.
ImageHandler *imageHandler = [ImageHandler alloc] init];
Returns the error "No known class method for selector 'alloc' which is true enough I guess, but how do I escape this? Will I have to base my swift-class of NSObject to avoid this?
In its simplest form: alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable. init: short for initialization, sets up the object and returns the object.
You can work with types declared in Swift from within the Objective-C code in your project by importing an Xcode-generated header file. This file is an Objective-C header that declares the Swift interfaces in your target, and you can think of it as an umbrella header for your Swift code.
Unfortunately, it's not possible to subclass a Swift class in Objective-C. Straight from the docs: You cannot subclass a Swift class in Objective-C.
This is an instance variable of the new instance that is initialized to a data structure describing the class; memory for all other instance variables is set to 0 . You must use an init... method to complete the initialization process. For example: TheClass *newObject = [[TheClass alloc] init];
You declare your ImageHandler
class as a root class. It doesn't have alloc
method itself. You need to inherit from NSObject
:
@objc class ImageHandler : NSObject { ... }
Referenced from this ADF thread.
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