b2cloud

26th June 2014

Convenient Swift Features (vs. Obj-C)

Guides | Tutorial By 2 years ago

Swift has made huge leaps over Objective-C when it comes to certain code-level features. This reduces the amount of code needed to be written to achieve the same, and also makes Swift code much more readable.

Writing loops

Now much easier in Swift

// Objective-C
for(NSUInteger i = 0; i < 10; i++) {
	// Code
}
// Swift
for i in 0..10 {
	// Code
}

Labelled breaks

You have probably seen the following code often. Simply, it’s a boolean in the scope of two for loops so the inner loop can break from the outer loop.

// Objective-C
BOOL shouldBreak = NO;

for(NSUInteger i = 0; i < 10; i++) {
	for(NSUInteger j = 0; j < 10; j++) {
		if(i == 2 && j == 5)
			shouldBreak = YES;
	}
	
	if(shouldBreak)
		break;
}

Now in Swift, loops can be labelled so you can specify which to break from.

// Swift
firstLoop: for i in 0..10 {
	secondLoop: for j in 0..10 {
		if i == 2 && j == 5 {
			break firstLoop
		}
	}
}

Concatenating strings

Because the parameters are all listed at the end, format strings in Objective-C make determining the final string harder for the programmer reading the code. In Swift, strings can be assembled using “string interpolation”, which lets you code dynamic data straight into the template string itself.

// Objective-C
const NSUInteger value1 = 15;
const NSUInteger value2 = 6;
const NSUInteger result = value1 + value2;
NSString* finalString = [NSString stringWithFormat:@"Calculation: %@ + %@ = %@", @(value1), @(value2), @(result)];
// "Calculation: 15 + 6 = 21"
// Swift
let value1 = 15
let value2 = 6
let result = value1 + value2
var finalString = "Calculation: \(value1) + \(value2) = \(result)"
// "Calculation: 15 + 6 = 21"

Modulo

Now the modulo operator works on floats and doubles. Hooray, no more custom functions.

Comparing strings

In Objective-C because NSString types were pointers, comparing strings had to be done via a method on the NSString class. Now that Swift is no longer is built upon C and pointers, strings can be compared via ==.

// Objective-C
if([string1 isEqualToString:string2]) {
	// Code
}
// Swift
if string1 == string2 {
	// Code
}

Class property initialization

In Objective-C all properties were given a default of nil for pointers, or 0 for primitives. In Swift, defaults can be specified before your init function is called, including assigning initialized classes as default values. You can even specify a closure for further customization.

// Swift
class MyClass {
	
	let someNumber = 123
	let someView = UIView()
	let someLabel: UILabel = {
		var result = UILabel()
		result.text = "Hey Ma'"
		result.textColor = UIColor.redColor()
		result.textAlignment = .Right
		return result
	}()
	
}

Switching any types, ranges, multiple values (tuples)

Objective-C was limited to the switch case functionality of C, which could only match constant integers. Swift now breaks free from these chains, and now you can switch any type of data, including strings, instances, ranges and tuples.

// Swift
switch self {
	
case UIApplication.sharedApplication():
	println("app")
	
case "hey":
	println("string")
	
default:
	println("other")
	
}
// Swift
let indexPath = NSIndexPath(forRow: 2, inSection: 5)

switch (indexPath.row, indexPath.section) {
	
case (1, 1):
	println("1,1")
	
case (2, 5):
	println("2,5")
	
default:
	println("other")
	
}
// Swift
let value = 50

switch value {
	
case 0...9:
	println("single digit")
	
case 10...99:
	println("double digits")
	
case 100...999:
	println("triple digits")
	
default:
	println("many digits")
	
}

Extending primitive types and structs (categories)

Categories in Objective-C could only be created on class types. In Swift extensions can be added to any type, including primatives and structs.

// Swift
extension Int {
	func addOne() -> Int {
		return self + 1
	}
}

let two = 1.addOne()

KVO and overriding setters/getters

In Objective-C it was common practice to either use KVO or a custom setter and getter to perform actions whenever a value of one of your properties was changed. Swift makes this way easier and less prone to error with simple hooks for your properties so you can perform custom code before and after a new value is set.

// Swift
class MyClass {
	
	var value: Int = 0 {
	willSet {
		// Cleanup before setting new value
	}
	didSet {
		// Actions after setting new value, eg: update the UI
	}
	}
	
}
  • Brandon Michael Zimmerman

    Swift is so much more intuitive and readable than Objective-C…and I love Obj-C!

Recommended Posts

Presenting UIViewController on launch in iOS 8

Post by 2 years ago

When you show a login screen or a walkthrough in your app, a common strategy is to present a view controller with no animation in your application:didFinishLaunchingWithOptions: method. In iOS 8 this has caused some

Got an idea?

We help entrepreneurs, organizations and established brands from around
the country bring ideas to life. We would love to hear from you!