Swift vs. Objective-C
Swift is the new programming language for iOS apps. Swift adds modern features that make programming easier and faster to write. Swift is a scripting language that will be familiar to Objective-C programmers and easy for newcomers to dig into.Here are some Swift code samples compared side-by-side with Objective-C:
Declaring variables (Swift)
let constantVariable = 50
Variables don't need to have their types assigned explicitly. Instead a variables type is acquired implicitly. I declare a contant integer in the sample above by using
var myVariable = 32
var myVariable2 = 70.0
var myVariable3 = "Hello World"let
and giving it a value of 50. The next three variables are all declared the using var
but they are all different types due to their assigned values, an integer, a double, and a string.
Declaring variables (Objective-C)
const int constantVariable = 50;
In contrast every variable in Objective-C must have its type assigned explicitly and every line of code must end with a
int myVariable = 32;
double myVariable2 = 70.0;
NSString *myVariable3 = @"Hello World";;
.
Including values in strings (Swift)
var width = 50
Adding variables into a string to be displayed is as simple as writing
var length = 80
var objectSummary = "The width of the object is (width) and the length is
(length)"(variable Name)
within the string.
Including values in strings (Objective-C)
int width = 50;
In Objective-C the string needs to be formatted with the values that it will receive. The correct type of value must be explicitly stated by using %d for integers, %f for floating point numbers, etc.
int length = 80;
NSString *objectSummary =
[NSString stringWithFormat:@"The width of the object is %d and the length is %d",width,length];
If-Statements, Loops, and Arrays (Swift)
let individualScores = [75, 43, 103, 87, 12]
Creating arrays and dictionaries in Swift is as simple as using brackets
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
println(teamScore)[]
. To access their elements you can write the element name or key within brackets like so myArray[myElement]
. The example above shows an array of scores with an enhanced for loop iterating through every element in the array.
If-Statements, Loops, and Arrays (Objective-C)
NSArray *individualScores = [NSArray arrayWithObjects:[NSNumber numberWithInt:75],
Assigning values to an array in Objective-C can become very tedious this is a clear example of what Swift is trying to improve.
[NSNumber numberWithInt:43],[NSNumber numberWithInt:103],
[NSNumber numberWithInt:87],[NSNumber numberWithInt:12],nil];
int teamScore = 0;
for (NSNumber *score in individualScores) {
if ([score integerValue] > 50) {
teamScore += 3;
} else {
teamScore +=1;
}
}
NSLog(@"%d",teamScore);