Hello I am currently importing a project from objective C to swift. The objective C project uses a custom library which in one of the classes it has a function that takes a Class object, which, when the data is loaded it initializes an id obj with the class(code below). On the objective C side this works great! I am using the same library on swift with a bridge header but unfortunately my object is nil once the data is loaded. I verified the data object used to initialize the object has content. The custom swift class also requires me to implement an init(data: Data) initializer when I add a custom init(), I am new to swift any help would be great! Thank you!
Objective C:
Library:
-(id) buildRetObject:(Class)clss fromData(NSData*) data{
id obj = nil;
if (data != nil) {
obj = [[clss alloc] initWithData:data];
}
}
Custom Object, is a subclass of another custom object, not in library but on main app:
Item.m:
-(id)init{
if ([super init]){
//do something
}
return self
}
Same Item object in swift:
//customClass super class is abstactCustomClass which is a sub abstract class of NSObject class, init functions are in here, the abstract class
class Item: customClass {
//variables
override init() {
super.init()
// do something
}
required init!(data: Data){
//fatalError(message here)
/*tried calling supers method
super.init(data:Data) gives error: fatal error: use of unimplemented initializer 'init(dictionary:)'*/
}
//methods
}
After a lot of digging I was finally able to figure it out, objective C knows from the abstract class what the initializers are, swift doesn't. So all I need to do was implement this initializers and it works.
required init!(data: Data){
super.init(data:Data)
}
override init(dictionary: [AnyHashable: Any]!){
super.init(Dictionary:dictionary)
}
Related
I have a custom class with a custom init written in swift. I need to call that init from an Objective-C class.
Swift
#objc public class MyClass: NSObject {
public init(configuration config: Data)
{
super.init()
// Do Stuff
}
}
Objective-C
[[MyClass alloc] initWithConfiguration:CONFIG];
But when I call the init from Objective-C the compiler complains that
No visible #interface for 'MyClass' declares the selector
'initWithConfiguration:'
What am I missing here?
You have to add #objc attribute to initializers too. Like this:
#objc public init(configuration config: Data)
{
super.init()
// Do Stuff
}
And after this, don't forget to re-build (CMD+B), otherwise Xcode will stupidly emit an error.
In Objective-C, NSObject had a class method called load that gets called when the class is loaded for the first time. What is the equivalent in Swift?
#implementation MyClass
+ (void)load
{
[self registerClass];
}
#end
Prior to Swift 1.2:
override class func load() {
NSLog("load");
}
EDIT:
As of Swift 1.2 you can no longer override the load method. Look into the method initialize instead, it behaves different than load though, it get's called the first time the class is being referenced somewhere rather than on application initial load
Support for overriding load was removed in Swift 1.2
Update: Starting from Swift 5 class extensions and categories on Swift classes are not allowed to have +load methods, +initialize doesn’t seem to be prohibited, though.
While direct equivalent is not available with Swift, this can be achieved relatively elegantly with Objective-C and categories. Foo should still inherit from NSObject and have a class / static non-private swiftyLoad/Initialize methods, which get invoked from Objective-C in Loader.m, which you include in compile sources alongside Foo.swift:
# Loader.m
#import <Foundation/Foundation.h>
#import <MyProject/MyProject-Swift.h>
// This was a more concise solution in Swift 4.2 and earlier. If you try
// this with Swift 5 you'd get "Swift class extensions and categories
// on Swift classes are not allowed to have +load methods" runtime error.
// #implementation Foo (private)
// + (void)load { [self swiftyLoad]; }
// + (void)initialize { [self swiftyInitialize]; }
// #end
// This is what you'd want to use with Swift 5 onwards, basically
// just a pure Objective-C defined class.
#interface Loader : NSObject
#end
#implementation Loader : NSObject
+ (void)load { [Foo swiftyLoad]; }
+ (void)initialize { [Foo swiftyInitialize]; }
#end
# Foo.swift
import Foundation
public class Foo: NSObject {
#objc public static func swiftyLoad() {
Swift.print("Rock 'n' roll!")
}
#objc public static func swiftyInitialize() {
Swift.print("Hello initialize!")
}
}
The best part there's no need to mess with bridging headers or anything else, it just works. There are couple of gotchas, especially when using this approach in static libraries, check out the complete post on Medium for details! ✌️
in Swift 2.0, Please use this method
public override class func initialize()
What is the equivalent in Swift?
There is none.
Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.
Source: "The Swift Programming Language", by Apple
Types simply don't have an initializer in Swift. As several answers here suggest, you may be able to work around that by using the Objective-C bridge and having your Swift class inherit from NSObject or by using a Objective-C loader bootstrap code but if you have a 100% Swift project, you basically only have two options:
Manually initialize your classes somewhere within the code:
class MyCoolClass {
static func initClass ( ) {
// Do your init stuff here...
}
}
// Somewhere in a method/function that is guaranteed to be called
// on app startup or at some other relevant event:
MyCoolClass.initClass()
Use a run once pattern in all methods that require an initialized class:
class MyCoolClass {
private static var classInitialized: Bool = {
// Do your init stuff here...
// This code will for sure only run once!
return true
}()
private static func ensureClassIsInitialized ( ) {
_ = self.classInitialized
}
func whateverA ( ... ) {
MyCoolClass.ensureClassIsInitialized()
// Do something...
}
func whateverB ( ... ) {
MyCoolClass.ensureClassIsInitialized()
// Do something...
}
func whateverC ( ... ) {
MyCoolClass.ensureClassIsInitialized()
// Do something...
}
}
This follows a clean pattern that no code in Swift runs "automagically", code only runs if other code instructs it to run, which provides a clear and trackable code flow.
There might be a better solution for special cases yet you have not provided any information as for why you need that feature to begin with.
The abilitity to use this method was removed in this PR.
It provides some rationale:
Swift's language model doesn't guarantee that type metadata will ever really be used, which makes overriding initialize() error-prone and not really any better than manually invoking an initialization function. Warn about this for Swift 3 compatibility and reject attempts to override +initialize in Swift 4.
For Swift 2 or 3 (i.e. post-Swift 1.2), you can use:
class MySwiftClass: NSObject {
internal override class func initialize() {
DoStuff()
super.initialize()
}
}
But, as you can see, your class needs to inherit (directly or indirectly) form NSObject. This is required because the initialize() is called by the ObjC runtime.
And the initialize() method will only be called when MySwiftClass is referenced. So it will not be as magic as load().
But it will also be safer. For example: including a framework (let's say, by just adding it to your Podfile) won't allow the framework to mysteriously start to behave as soon as your app launches, without the need to add a single line of code to your project (at least… I hope! 😉).
I get conclusion for swift 1.2~5 doable ways:
Doable |swift-load |swift-initialze|bridgeToOC-load|bridgeToOC-initialze|
--- |---- |--- |--- |--- |
swift1.2~4.2|X |O |O |O |
swift4.2~5.0|X |X |O |O |
swift5.0~? |X |X |X |O |
and how to make it ? check here
https://medium.com/post-mortem/using-nsobjects-load-and-initialize-from-swift-f6f2c6d9aad0
but I think here is another way to make it swifter. use runtime and protol without load/initialze.
http://jordansmith.io/handling-the-deprecation-of-initialize/
Swift 5
Method 'load()' defines Objective-C class method 'load', which is not permitted by Swift
You can not override load() method now but there is a legal way to call your custom swift_load() method of your swift classes on app startup. It is needed to make ObjC class which redirect its own load() method to your swift classes.
Just add next SwiftLoader.m file to your project:
// SwiftLoader.m
#interface SwiftLoader : NSObject
#end
#implementation SwiftLoader
+ (void)load {
SEL selector = #selector(swift_load);
int numClasses = objc_getClassList(NULL, 0);
Class* classes = (Class *)malloc(sizeof(Class) * numClasses);
numClasses = objc_getClassList(classes, numClasses);
for (int i = 0; i < numClasses; i++) {
Class class = classes[i];
Method method = class_getClassMethod(class, selector);
if (method != NULL) {
IMP imp = method_getImplementation(method);
((id (*)(Class, SEL))imp)(class, selector);
}
}
free(classes);
}
Now you can add swift_load class method to any of your swift classes to make setup tasks:
class MyClass {
#objc
class func swift_load() {
print("load")
}
}
I am working on a Swift metawear (mbientlab.com) project and all the code examples are in Objective C so have to do lots of conversion. Following this blog post - http://projects.mbientlab.com/persistent-events-and-filters/ - I created the following class that inherits from MBLRestorable (which implements the NSCoder protocol):
class DeviceConfiguration:NSObject, MBLRestorable {
var pulseWithEvent:MBLEvent!
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.pulseWithEvent, forKey: "pulseWithEvent")
}
required init(coder aDecoder: NSCoder) {
super.init()
self.pulseWithEvent = aDecoder.decodeObjectForKey("pulseWithEvent") as MBLEvent
}
}
So far so good. Now I am converting the following Objective C to Swift:
[self.device setConfiguration:[[DeviceConfiguration alloc] init] handler:^(NSError *error) {
if (!error) {
// Programming successful!
}
}];
I try:
self.device.setConfiguration(MetawearConfig()) { error in
}
But get an error that it is missing the required argument "coder." Make sense to me that it would require that param on init but in the Objective C sample code/applications a coder obj is never passed in (and the compiler does not raise the same error).
The declaration for setConfiguration is:
- (void)setConfiguration:(id<MBLRestorable>)configuration handler:(MBLErrorHandler)handler;
What I am missing?
You're calling MetawearConfig(), but the only init you provide is init(coder aDecoder: NSCoder). If you want a non-parameter init, you must provide one:
init() {
// initialize your object
}
Swift classes do not by default inherit the superclass's initializers (See Swift language guide -> Initialization -> search for section "Automatic Initializer Inheritance"). NSObject's init() is a "designated initializer". Designated initializers are only inherited by a subclass if the subclass implements no designated initializers of its own. Since your DeviceConfiguration class implements a designated initializer init(coder:), it does not inherit designated initializers from its superclass. That's why DeviceConfiguration does not have an initializer with signature init().
Objective-C is different in that initializers are just methods in Objective-C and are always inherited.
The DeviceConfiguration in Objective-C would also have a different init with no parameters, inherited from NSObject. The code you're converting looks to be calling the no-parameter version rather than the NSCoder version.
In Objective-C, NSObject had a class method called load that gets called when the class is loaded for the first time. What is the equivalent in Swift?
#implementation MyClass
+ (void)load
{
[self registerClass];
}
#end
Prior to Swift 1.2:
override class func load() {
NSLog("load");
}
EDIT:
As of Swift 1.2 you can no longer override the load method. Look into the method initialize instead, it behaves different than load though, it get's called the first time the class is being referenced somewhere rather than on application initial load
Support for overriding load was removed in Swift 1.2
Update: Starting from Swift 5 class extensions and categories on Swift classes are not allowed to have +load methods, +initialize doesn’t seem to be prohibited, though.
While direct equivalent is not available with Swift, this can be achieved relatively elegantly with Objective-C and categories. Foo should still inherit from NSObject and have a class / static non-private swiftyLoad/Initialize methods, which get invoked from Objective-C in Loader.m, which you include in compile sources alongside Foo.swift:
# Loader.m
#import <Foundation/Foundation.h>
#import <MyProject/MyProject-Swift.h>
// This was a more concise solution in Swift 4.2 and earlier. If you try
// this with Swift 5 you'd get "Swift class extensions and categories
// on Swift classes are not allowed to have +load methods" runtime error.
// #implementation Foo (private)
// + (void)load { [self swiftyLoad]; }
// + (void)initialize { [self swiftyInitialize]; }
// #end
// This is what you'd want to use with Swift 5 onwards, basically
// just a pure Objective-C defined class.
#interface Loader : NSObject
#end
#implementation Loader : NSObject
+ (void)load { [Foo swiftyLoad]; }
+ (void)initialize { [Foo swiftyInitialize]; }
#end
# Foo.swift
import Foundation
public class Foo: NSObject {
#objc public static func swiftyLoad() {
Swift.print("Rock 'n' roll!")
}
#objc public static func swiftyInitialize() {
Swift.print("Hello initialize!")
}
}
The best part there's no need to mess with bridging headers or anything else, it just works. There are couple of gotchas, especially when using this approach in static libraries, check out the complete post on Medium for details! ✌️
in Swift 2.0, Please use this method
public override class func initialize()
What is the equivalent in Swift?
There is none.
Unlike stored instance properties, you must always give stored type properties a default value. This is because the type itself does not have an initializer that can assign a value to a stored type property at initialization time.
Source: "The Swift Programming Language", by Apple
Types simply don't have an initializer in Swift. As several answers here suggest, you may be able to work around that by using the Objective-C bridge and having your Swift class inherit from NSObject or by using a Objective-C loader bootstrap code but if you have a 100% Swift project, you basically only have two options:
Manually initialize your classes somewhere within the code:
class MyCoolClass {
static func initClass ( ) {
// Do your init stuff here...
}
}
// Somewhere in a method/function that is guaranteed to be called
// on app startup or at some other relevant event:
MyCoolClass.initClass()
Use a run once pattern in all methods that require an initialized class:
class MyCoolClass {
private static var classInitialized: Bool = {
// Do your init stuff here...
// This code will for sure only run once!
return true
}()
private static func ensureClassIsInitialized ( ) {
_ = self.classInitialized
}
func whateverA ( ... ) {
MyCoolClass.ensureClassIsInitialized()
// Do something...
}
func whateverB ( ... ) {
MyCoolClass.ensureClassIsInitialized()
// Do something...
}
func whateverC ( ... ) {
MyCoolClass.ensureClassIsInitialized()
// Do something...
}
}
This follows a clean pattern that no code in Swift runs "automagically", code only runs if other code instructs it to run, which provides a clear and trackable code flow.
There might be a better solution for special cases yet you have not provided any information as for why you need that feature to begin with.
The abilitity to use this method was removed in this PR.
It provides some rationale:
Swift's language model doesn't guarantee that type metadata will ever really be used, which makes overriding initialize() error-prone and not really any better than manually invoking an initialization function. Warn about this for Swift 3 compatibility and reject attempts to override +initialize in Swift 4.
For Swift 2 or 3 (i.e. post-Swift 1.2), you can use:
class MySwiftClass: NSObject {
internal override class func initialize() {
DoStuff()
super.initialize()
}
}
But, as you can see, your class needs to inherit (directly or indirectly) form NSObject. This is required because the initialize() is called by the ObjC runtime.
And the initialize() method will only be called when MySwiftClass is referenced. So it will not be as magic as load().
But it will also be safer. For example: including a framework (let's say, by just adding it to your Podfile) won't allow the framework to mysteriously start to behave as soon as your app launches, without the need to add a single line of code to your project (at least… I hope! 😉).
I get conclusion for swift 1.2~5 doable ways:
Doable |swift-load |swift-initialze|bridgeToOC-load|bridgeToOC-initialze|
--- |---- |--- |--- |--- |
swift1.2~4.2|X |O |O |O |
swift4.2~5.0|X |X |O |O |
swift5.0~? |X |X |X |O |
and how to make it ? check here
https://medium.com/post-mortem/using-nsobjects-load-and-initialize-from-swift-f6f2c6d9aad0
but I think here is another way to make it swifter. use runtime and protol without load/initialze.
http://jordansmith.io/handling-the-deprecation-of-initialize/
Swift 5
Method 'load()' defines Objective-C class method 'load', which is not permitted by Swift
You can not override load() method now but there is a legal way to call your custom swift_load() method of your swift classes on app startup. It is needed to make ObjC class which redirect its own load() method to your swift classes.
Just add next SwiftLoader.m file to your project:
// SwiftLoader.m
#interface SwiftLoader : NSObject
#end
#implementation SwiftLoader
+ (void)load {
SEL selector = #selector(swift_load);
int numClasses = objc_getClassList(NULL, 0);
Class* classes = (Class *)malloc(sizeof(Class) * numClasses);
numClasses = objc_getClassList(classes, numClasses);
for (int i = 0; i < numClasses; i++) {
Class class = classes[i];
Method method = class_getClassMethod(class, selector);
if (method != NULL) {
IMP imp = method_getImplementation(method);
((id (*)(Class, SEL))imp)(class, selector);
}
}
free(classes);
}
Now you can add swift_load class method to any of your swift classes to make setup tasks:
class MyClass {
#objc
class func swift_load() {
print("load")
}
}
if I declare the swift constant as a global constant like:
let a = "123"
but the a cannot be found in objective c.
How to solve this?
From Apple Doc:
You’ll have access to anything within a class or protocol that’s marked with the #objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:
Generics
Tuples
Enumerations defined in Swift
Structures defined in Swift
Top-level functions defined in Swift
Global variables defined in Swift
Typealiases defined in Swift
Swift-style variadics
Nested types
Curried functions
Therefore its not possible to access global variables(Constants) or global functions defined in Swift.
Possible Solutions:
From the Apple Document Swift programming language, You can Declare Type Properties as
class var constant: Int = {
return 10
}()
But currently in Swift(beta-3) Type properties are not supported.
You can declare a Class function to get a constant value:
In Swift:
class func myConst() -> String {
return "Your constant"
}
Accessing from Objective-C:
NSString *constantValue = [ClassName myConst];
NSLog(#"%#", constantValue);
Swift code:
public class MyClass: NSObject {
public static let myConst = "aConst"
}
and then in Objective-C:
[MyClass myConst]
Isn't this working as well? As in this works for me.
Also this is somewhat shorter as creating a object first (alloc, init). Making a new function for every constant is... not pretty :/
Update for Swift 4
Because of the changes in Swift 4's Objective-C inference, you need to add the #objc annotation to the declared constant as well. The previous declaration then becomes:
#objcMembers
public class MyClass: NSObject {
public static let myConst = "aConst"
}
The calling Objective-C code remains the same.
Using #objcMembers makes all constants available (as if you'd write #objc before each constant), but I've had times where the compiler somehow wouldn't generate the corresponding ObjC code.
In those cases I'd suggest adding the #objc decorator before the constant as well.
I.e.: #objc public static let myConst = "aConst"
You should not have any problem by using let in Objective-C, next example was made with Xcode 7.2 :
MyClass.swift
import Foundation
import UIKit
#objc class MyClass : NSObject { // <== #objc AND NSObject ARE BOTH NECESSARY!!!
let my_color = UIColor( red:128/255,green:32/255,blue:64/255,alpha:1 ) // <== CONSTANT!!!
}
MyObjectiveC.m
#import "PROJECTNAME-Swift.h" // <== NECESSARY TO RECOGNIZE SWIFT CLASSES!!!
#interface MyObjectiveC ()
#end
#implementation MyObjectiveC
#synthesize tableview; // <== ANY UI OBJECT, JUST AS EXAMPLE!!!
- (void) viewDidLoad () {
MyClass * mc = [ [ MyClass alloc ] init ]; // <== INSTANTIATE SWIFT CLASS!!!
tableview.backgroundColor = mc.my_color; // <== USE THE CONSTANT!!!
}
#end
PROJECTNAME is the name of your Xcode project, as shown in Project Navigator.
In your swift class,
let constant: Float = -1
class YourClass: NSObject {
class func getMyConstant() -> Float {return constant}
...
}
Clean, build to let xcode prepare this method useable for obj-c.
Then at your obj-c class
if ([YourClass getMyConstant] != 0) {
...
}
First of all you need to know about the important of auto-generated Swift header file.
It is the one that will made the magic to transcribe the Swift code to be understandable from Objective-C.
This file is auto-generated by Xcode (do not look for it in your project).
The important of this file is to use the correct name, it can match with your target name, but, may not, it is the product module name. (Search for it in your project settings as "Product module")
You need to import this file on the Objective-C class that you want to use a Swift class and also the Swift class name of your Swift file.
#import <ProductModuleName-Swift.h>
#class MySwiftClassName;
My Swift class should have the prefix #objc and inherit from NSObject:
#objc class MySwiftClassName: NSObject {
let mySwiftVar = "123"
}
Then you can call your Swift variable from the Objective-C file:
MySwiftClassName *mySwiftClassO = [[MySwiftClassName alloc] init];
NSString *myVar = mySwiftClassO.mySwiftVar;
Make sure to clean and rebuild your project after each change to force regenerate this auto-generated file.
If your Swift header file was auto-generated correctly you can navigate to it by clicking over the import file name and check if all the code you need was properly transcribed.
In the following post you can find more detailed information about this. https://solidgeargroup.com/bridging-swift-objective-c
Classes func don't work. The only solution I have found out is this one:
class YourController: NSObject {
#objc static let shared = YourController()
private override init() { }
#objc class func sharedInstance() -> YourController {
return YourController.shared
}
#objc let terms = "Your-String-here"
And then on Obj-c file:
[[YourController sharedInstance].terms]