Posts

Showing posts from October, 2018

Use Swift Class in Objective C

Image
Sometimes we would like to include the Code written in the Swift Language to be used in Objective-C file. Recently, I ran into a situation where I need to use my Swift written code into Objective-C .m file. Before we start this, we need to understand @objc . It's an attribute which helps the swift code interoperability with Objective-C code. Consider the below code: class User : NSObject {     init ( _ nameId: Int ) { }     init ( _ name: String ) { } } Here, the 'User' can be initialized by nameId or name, but Objective-C does not understand this short hand implementation. It would not know which initialization to call , one with nameId or one with just  name. class User : NSObject {     @objc(initWithNameID:) init ( _ nameId: Int ) { }     @objc(initWithName:) init ( _ name: String ) { } } The Objective-c code will now know there are two initialization methods, one initWithNameID   and   initWithName . @objc(initWit

Variadic Parameters in Swift

Image
Variadic Parameters allows us to specific 'n' number for parameters to a function. This could be useful in scenarios where input count is unknown. ex: Addition of all numbers. Below is a simple function implementation in Swift . func addNumbers(addAllNumbers numberItems: Int ...) -> Int {     var total = 0     for num in numberItems {         total += num     }          return total } addNumbers (addAllNumbers: 1 , 2 , 3 ) The answer this would be 6. Here we don't have to pass a array of Int, instead of that we pass input's as if there are multiple parameters (not inputs are ',' separated). Now one important question arises here, Can a function have more than one variadic kind of parameter?  Answer to this is NO. There can be only one and only one variadic parameter. Try to that and you will get the compile time error, as shown below.