How Swift Programming language is similar and different from Objective-C

Similarities to Objective-C

  • Basic numeric types (Int, UInt, Float, Double)
  • Most C operators are carried over to Swift, but there are some new operators
  • Curly braces are used to group statements.
  • Variables are assigned using an equals sign, but compared using two consecutive equals signs. A new identity operator, ===, is provided to check if two data elements refer to the same object.
  • Square brackets are used with arrays, both to declare them and to get a value at a given index in one of them.
  • Control statements, for, while, if, switch are similar, but have extended functionality, e.g. a for in that iterates over any collection type, a switch that takes non-integer cases, etc.
  • Class methods are inherited, just like instance methods; self in class methods is the class the method was called on.

Differences from Objective-C

  • Statements do not need to end with a semicolon (‘;’), though they may be used to allow more than one statement on a line
  • Header files are not required
  • Comments of the form /* … */ can be nested, allowing blocks of code to be easily commented out.
  • Strong typing
  • Type inference
  • Generic programming
  • Functions are first-class objects.
  • Operators can be redefined for classes (operator overloading), and new operators can be created.
  • Strings fully support Unicode. Most, but not all, Unicode characters can be used in Swift language names.
  • Several notoriously error-prone behaviors of C-family languages have been changed:
  • No pointers exist. There is no need for the programmer to keep track of and mark names for referencing or de-referencing.
  • Assignments do not return a value. Thus the common mistake of writing if (i=0) when if (i==0) is meant will cause a compile-time error.
  • No need to use break statements in switch blocks. Individual cases do not fall through to the next case unless the fallthrough statement is used.
  • Variables and constants are always initialized and array bounds are always checked.
  • Overflows, which are undefined behaviors for signed integers in C, are trapped as a run-time error, but programmers can choose to allow overflows by using the special arithmetical operators &+, &-, &*, &/ and &%. Properties min and max are defined in Swift for all integer types and can be used to safely check for potential overflows, as contrasted with relying on constants defined for each type in external libraries.