Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Swift initializer (that has a parameter) from Objective-C?

I have a Swift class:

class MyTextField : NSObject, UITextFieldDelegate { 

    var myField: UITextField

    // no idea how to pass in my UITextField from Objective-C code
    init (x: UITextField) {
        myField = x;
    }
}

I have added a property (not shown) so I could set myField, and everything is working.

Would like to use the init function, if only the syntax were not a complete mystery. Any ideas?

like image 822
Gerry Avatar asked Sep 18 '14 22:09

Gerry


People also ask

Can you call Swift from Objective-C?

Overview. 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.

How do you inherit a Swift class in Objective-C?

Swift classes that are inherited from OBJC classes are bridged automatically. That means any class inherited from, for example, UIViewController is automatically seen in the OBJC runtime. If you're creating a class that doesn't inherit from anything, then make it an NSObject subclass, as you would in OBJC.

Can you mix Objective-C and Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

How do you call a function in Objective-C?

An Objective-C function is declared using the following syntax: <return type> <function name> (<arg1 type> <arg1 name>, <arg2 type> <arg2 name>, ... ) Explanations of the various fields of the function declaration are as follows: <return type> - Specifies the data type of the result returned by the function.


1 Answers

Call it the same way you'd call an Obj-C initializer, so for your example, you'd call [[MyTextField alloc] initWithX:theTextField];.

like image 52
NRitH Avatar answered Oct 26 '22 13:10

NRitH