Showing posts with label Objective C. Show all posts
Showing posts with label Objective C. Show all posts

Wednesday, January 8, 2020

How you can Switch your apps from Objective C to Swift?

When Apple Inc. has released the first iPhone SDK in 2007 and insist outsider developers to make iPhone applications, it has declared Objective-C as official iOS programming language supporting Xcode as a development tool and IDE. Swift offers many advantages like, writing less code, less maintenance of apps, speed up app development process, less bugs and crashes, strong security and so on. If you have been working on Objective C, it is the right time to shift over Swift. A large number of the well known iOS applications like Yahoo, LinkedIn, Lyft, Weather and so on have effectively headed out from Objective-C to Swift effectively.

Objective C to Swift Converter-

Apple offers modern Objective-C converter in X-code. This helps developers to do some significant things during conversion. These things are – Implementing Enum Macros, Changing ID to Instance Type, helps in updating @proprty syntax. We should keep in mind that converter helps in detection and also implementation of mechanics of potential changes. It will never represent the semantics of the code. It implies iOS developers need to go manually for alterations and improve the quality of Swift code also. To use converter in X code-
Edit → Convert → To Modern Objective-C Syntax

Tips While Using Objective C to Swift Converter-

Switch apps from Objective C to Swift

1. Convert One Class at a Time-

Always remember that, you cannot convert all your code from Objective-C to Swift at once. To do this, you have to choose one class at a time. A few classes are written in Swift while others in Objective-C. And you get a hybrid target once the Swift file added to Objective-C application target. Swift can’t have subclasses. Hence you can pick two files to be specific a header file, which is .h and contains @interface section and a .m file that contains @implementation section. You don’t need to develop a header file as the .m document imports the .h file if it needs to refer to a class.

2. Creating a Bridging Header-

When you include an Objective-C file into Swift target or vice versa, you will have opportunities to develop a bridging header file. Hence, when you import (.h) record into bridging over header, it gets visible to Swift.

3. Performing the Nil Checks-

In the Objective-C programming when a message is sent to a nil object, you eventually get a zero value in return. Hence, if you need to avoid  this from getting a nil value, it is necessary to opt for the nil checks according to the requirements. Normally, you get it as a generic enum-
public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible
In a normal case you get both of  two; a value of Wrapped type or a value that doesn’t exist.

4. Wrapped Value-

With swift you have another benefit. You also get the syntactic sugar for stating the types optional. It enables you to substitute the Optional<String> with String? You can get the wrapped value from the elective container utilizing two techniques- Optional Chaining and Forced Wrapping. In the primary case, it is used if the conditional statement acquires a value in case of its existence. With second case, the conditional statement isn’t nil. In the event that it contains a variable you would get an outcome without applying conditions or else it would crash. The completely unwrapped optional in Swift is known as the String. It can be shown through an example:
class ExampleClass {
   var nonOptionalString: String
   var unwrappedOptionalString: String!
   var optionalString: String?
   init(string: String) {
       nonOptionalString = string
   }
}
All things considered, you can go over three possibilities which can land at this point.
  1. The first is that of nonoptinalString. It’s value will never be a zero. It should contain a variable when object is getting initialized or it will crash.
  2. Next is unwrappedOptionalString where the value of string is nil. Thus, if you are trying to get over a nothing value object, the program will crash.
  3. Last is optionalString where the string remains nil yet is taken as a normal optional variable.
Along these lines, when composing the Objective-C code, better categorize your variables into two distinct classes; Nullable and _Nonnull type annotation.
Therefore, the earlier indicated illustration would resemble something like this:
@interface ExampleClass: NSObject
@property (nonatomic, strong) NSString * _Nonnull nonOptionalString;
@property (nonatomic, strong) NSString *unwrappedOptionalString;
@property (nonatomic, strong) NSString * _Nullable optionalString;
- (instancetype)initWithString:(nonnull NSString *string);
@end

5. Tuples-

Apple has also presented new development language called Tuples. It groups different values into one compound value and is a better tool in the event that you are developing a model at a place and directly isn’t easy to understand.

6. Extensions-

The extensions in the Objective-C language are combined into a single entity in Swift. It offers another functionality to the current class, structure and protocol and there is no need to avail the source code for extending types.

7. Enumerations-

The Objective-C limits the code enumerations to the primitive types only.
If you want to map the integer enumeration value to the consequent strings for demonstrating results to the user or sending to the backend an array is required.
But, Swift makes you convenient as you don’t need to experience these complexities. It is offering new enumerations with more options.
enum ExampleEnum {
    case ExOne, ExTwo, ExThree
}
It can store the related values and you can store raw values in Swift enumerations using it like as Objective-C.
enum AnotherExampleEnum {
   case ExOne(String, Int)
   case ExTwo(Int)
}

8. Subscripts-

These are generally used to get data from a group or group of classes’ structures or enumerations without utilizing any technique. Subscripts help in regaining the values by index and as such you don’t need to store or retrieve. The elements in Array instance can be seen as someArray (index) and for Directory instance as someDictionary [key]. Just follow the syntax:
subscript (index: Int) -> Int {
get {
//for declaring subscript value
}
set (newValue) {
//for defining values
}
}

9. Type Implication-

Type safety for the iOS development usually refers to an integer which is declared with a specific type. It can not be altered and remains fixed. The compiler decides what variable type will continue as indicated by the given value.
For example:
var str = "One String"
// OR
var str2:String
Str2 = "Second String"
When you are attempting to start by putting number values to a str2 variable, the compiler is said to show an error.
Str2 = 10 //error: Cannot put value of type 'Int' to type 'String'

10. Function-

Swift offers a simpler approach with regards to the function syntax. Each function includes a type. And type contains function’s parameter types and return type. It allows you to either allocate a function to variable or pass it as a value. The application developers can also give default value to parameter.
func stringCharacterscount (s: String) -> Int
   {
return s.characters.count
   }
func stringToInt (s: String) -> Int
   {
if let a = Int (s)
   {
return a
   }
return 0
   }
func executeSuccessor (f: String -> Int, s: String) -> Int
   {
Return f(s). successor()
   }
let f1 = stringCharacterscount
let f2 = stringToInt
 
executeSuccessor (f1, s: "5555") //5
executeSuccessor (f2, s: "5555") //5556

11. Dealing with Errors-

In this way, when you are managing the errors in Objective-C you need to use the reference to NSError variable. But, if this approach is not appropriate, you need to develop an NSError instance and write to passed variable. You need to check the error parameter and verify that it is non-nil.
- (nonnull NSString *)exampleMethod:(nonnull NSString *)param error:(NSError **)error {
   if (!param.length) {
       *error = [NSError errorWithDomain:[NSBundle mainBundle].bundleIdentifier code:-10 userInfo:nil];
   return nil;
   }
   // do work
}
In case of Swift you get circulating, throwing, catching and controlling errors that can be recovered.

Conversion Process-

  1. Choose a pair of (.h) and (.m) files you want to convert.
  2. Search #import “MyViewController.h” across the code document and remove it.
  3. In all .m files, you have to replace #import “[filename].h” instances with #import “[MyProject]-Swift.h”
  4. In all the .h files, replace @class [filename] with #import “[filename].h”
  5. Transform Objective C files to Swift using Swiftify Xcode Extension
  6. The .h and .m files have to be replaced from project with the converted .swift file.
  7. Now, it is time to fix the conversion error, and Swiftify extension can help you in this regard.
  8. Now, you can build and run the project smoothly.
  9. If you have chosen to convert the entire project, you can transform AppDelegate class now.

Conclusion

Swift has rightly become one of the top options for the swift developers. With this new programming language, Apple offers a few advantages over Objective-C. Most developers have just decided to convert their applications from Objective C to Swift. The transformation must be done cautiously without missing any step. Also you need an experienced professional to carry out this job. 
If you are thinking to do the same, connect with solace team. Experts at solace are well proficient in new trends and technologies and will surely give you the best solution as you desire. We will be happy to help you.

Monday, August 5, 2019

Swift VS Objective-C: Which language to Choose in 2019?


Read More at-
Objective-C is the primary programming language that you can use for developing software for iOS. This language is a superset of the C programming language. It provides object-oriented capabilities and a dynamic runtime. While, in 2014, Apple launched Swift programming language for iOS mobile apps. This language is an alternative to Object C, an object oriented superset of the C programming language. Swift programming language is designed to be compatible with all existing iOS development tools—xCode, Objective-C, and the Cocoa framework. It is safe to use and has improved features, so it is replacing the Objective C. 


Disadvantages of Objective C-

  1. As Objective-C is built on top of C, it lacks namespacing. All classes in an Objective-C application should be globally unique. So to avoid collision there is a convention of prefixing the names of classes. This is the reason we have the ‘NS’ prefix for the class in the Foundation Framework and the ‘UI’ prefix for the classes in UIKit.
  2. The ability to send a message on a nil object without crashing and the lack of strict typing lead to bugs that are hard to trace and fix.
  3. The language is syntactically verbose and complex, but this is expected given that it is a fairly old language.
  4. Explicit pointers.

Advantages of Swift of being more popular-

  1. It is an open source programming language.
  2. Swift has a huge development community
  3. it is faster, safer and easier to read and write
  4. it supports dynamic libraries
  5. Swift has better memory management.
Here we will see the reasons why one should use Swift for next iOS app development.

1. Swift is Faster-

New technologies need high speed of performance, and Swift is totally fulfilling this need. According to test analysis, it shows the same performance as C++ for the FFT and Mandelbrot algorithms. Swift is more young language so many improvements are going to be done in the future.
The reason why everyone is buzzing about the future of swift is simple that Swift is rapidly developing language. 

2. Easy to read and write-

Reason behind more use of Swift is its simple syntax. Hence the reading and writing of code is easy. While, Objective C requires more symbols, semicolon to end line, parenthesis surrounding conditional expressions inside “if” or “else” statements, etc. Swift does not any of these. Whereas it uses comma-separated list of parameters within parentheses. Implementing any option in Swift requires writing fewer code strings than Objective C language. This avoids mistakes so the code becomes cleaner. As a result, developers require less time to complete a complex task. Swift is easily understandable for programmers using Java, JavaScript, Python, C# and C++. They can easily adopt code written in Swift.

3. Swift is Safer-

Remember the nil pointer variables (uninitialized) in Objective-C turning the expression to no-operation and leading to app crashes? Just forget about this issue when using Swift. Swift was designed with safety in mind. It produces a compiler error, whenever you write wrong code. This implies all the bugs can be fixed at development stage without assessing the whole code a while later. 

4. Better memory management- 

One of the problems at Objective-C is ARC (Automatic Reference Counting), that is supported within the Cocoa API and object-oriented code. However, the code is not available for procedural C code and such APIs as Core Graphics. That prompts the immense leakage of memory. Swift has solved this problem by making ARK complete with the procedural and object-oriented code paths. Due to this programmers can focus on the app logic and its features instead of managing memory within an app.

5. Dynamic Libraries-

As per above discussion, Swift is a fast developing language. It also allows you to update your apps as soon as the new Swift version arrives. This is possible due to the use of dynamic libraries, presented together with iOS 8. Previously, the static libraries updates were performed together with such major updates like the new iOS version. Dynamic libraries for their part, allow connecting pieces of code directly to the app. This helps to keep your project updated, reduces the initial size of the app, and also speeds up a load of external libraries and minimizes the time needed to load new content.
Migrating from Swift to Objective-C is easy, too. Developers can take advantage of Swift’s advanced features by replacing chunks of app code written in Objective-C with Swift.
Swift is designed to work with the Cocoa Touch framework; you’ll just need to set up a Swift development environment in Xcode. Then, import Cocoa frameworks, APIs, and Objective-C code modules to get started.

Disadvantages of Swift:

  1. Higher compile time.
  2. No direct way of using C++ libraries.
  3. Module format stability is still not achieved and is required for developers who want to share their code as a binary framework.

Conclusion-

Apple offers great interoperability between Objective-C and Swift. Also it is not dropping support for Objective-C in future. It is better for programmers to start migrating parts of their Objective-C code to Swift because it is ABI Stable now. Swift is now officially ABI stable and can be considered to be a mature language. The future updates in Swift would not break the current code written from now on in Swift 5.
  1. If you are developing a binary framework, you should suggest waiting for Swift to achieve Module Format Stability.
  2.  Also, if you are dealing with C++ and Objective-C++ codebase or framework, then you would need a mix of Objective-C and Swift. The Objective-C part can interface directly with the C++ or Objective-C++ parts of your code and the Swift part can then use Objective-C classes to interact with the C++ or Objective-C++ code.
Confused to choose the swift or Objective C for ios development? Contact us for a free consultation and solution regarding Swift vs Objective C. We at Solace are here to help your businesses to best ios development through our experts.