Skip to content

Learning Swift Notes

JinlianWang edited this page Feb 3, 2015 · 4 revisions

I have been to some presentations over Swift language, but never sit down and get my hand dirty. The reason is that 1) we can really go without swift now; 2) there are other new features that I want to get a hand of and try to use it for the projects as soon as possible. In other words, even though people are craving about swift, to me, it is just another new language, no more no less, whether or not adopt it is really a matter of whether it is worth it for the project. But I do want to spend some time learning it, after I went through other new iOS 8 features that I deem more important. This page captures some of the learning notes just in case I need to go back to it later or want to share with friends.

How to show a UIViewController that is implemented in Swift from an Objective C project?

It is interesting how hard I searched, no single tutorial out there talking about this topic: how do you call a new UIViewController (a piece of new interface) that is implemented in Swift, though there are tons of articles about a normal Swift class without an interface. But hey, the most likely way of integrating Swift is to implement a new feature in Swift and call it from old plain Objective C code. So here we go, I did a bit of research of my own. And here is the steps:

  • Add new "Cocoa Touch Class" to project, specifying class name as "SwiftViewController", extending from UIViewController, language in Swift, check "Also create NIB file";

  • Try to use this new UIViewController from Objective C code.

Observations:

  • Glitch 1: The new swift file would include import Cocoa, but it produces a compiler error. It should be changed to import UIKit instead; Not exactly why there is such an obvious glitch, but quite hard for beginner to figure out;

  • Glitch 2: While I type self.dismissViewControllerAnimated(true, completion: nil); to dismiss the view controller in Swift, the auto complete for true is bothering. It always presents TRUE which does not compile;

  • Glitch 3: To use Swift classes in Objective C, we need to import the umbrella header file, like #import "TestSwift2-swift.h", there is no auto complete for this header file;

  • Glitch 4: For a UIViewController in Objective C, you do not need to specify its nib file name if it is the same name as the .m file. However, in Swift, you have to load nib file explicitly, even if the nib file and .swift file share the same name:

SwiftViewController *controller = [[SwiftViewController alloc] initWithNibName:@"SwiftViewController" bundle:nil];
[self presentViewController:controller animated:YES completion:nil];
Clone this wiki locally