Skip to main content


Showing posts from June, 2014

How to write a method in Swift that accepts a closure

To write a method that accepts an anonymous closure is simple. It relies on using the accepts and returns syntax, written for example: (String)->String Once we understand this, a whole world of possibilities opens up. The start of which might be something like:  func myClosureMethod (name:String, processor:(String)->String) {         var newText = processor(name)         println(newText)     } The thing to note here is the way in which we call the closure, by treating the name of the closure like it was a method using processor() . We'd then call the method in this way: self.myClosureMethod("Peter Pan", processor: {textstring in "Hello " + textstring}) indicating a closure using the code braces, then assigning the parameter being sent to the closure a name – 'textstring' – and then manipulating it before the string is returned implicitly. Don't worry too much about the in word, it simply separates the parameter name

JSON and Xcode (iOS): The Swift Basics

Note: there is now a library called Aldwych on GitHub that handles JSON in Swift, and which I would highly recommend you take a look at. It solves the issues found here. (Disclaimer: I created the  library.) A while ago, I wrote a post called JSON and Xcode (iOS): The Basics . This post is an extension to that one and supplies an example of how to do the same thing as before but this time in Swift. Loading JSON and converting to Swift objects // Create filepath var filepath:String = NSBundle.mainBundle().pathForResource("hello", ofType: "json") // Create optional for NSError var error:NSError? // Retrieve Data var JSONData = NSData.dataWithContentsOfFile(filepath, options: NSDataReadingOptions.DataReadingMapped, error:&error) // Create another error optional var jsonerror:NSError? // We don't know the type of object we'll receive back so use AnyObject let swiftObject:AnyObject = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJS

Goodbye blocks: Passing a closure to a parameter in Swift (Xcode/iOS)

Problem Sooner or later you'll need to pass a closure to a parameter in Swift when using a Cocoa Touch framework. So let's do something simple to illustrate how this is done by looking at the method animateWithDuration, which has a declaration like this: class func animateWithDuration(duration: NSTimeInterval, animations: (() -> Void)!, completion: ((Bool) -> Void)!) So here we see that the animations parameter requires a closure that receives no parameters and returns Void, while the completion parameter must accept a Bool and return void. Solution(s) UIView.animateWithDuration(2.0, animations: {()->Void in self.view.backgroundColor=UIColor.brownColor()}, completion: {(finished:Bool)->Void in self.view.backgroundColor=UIColor.yellowColor()}) The line of code that I've written above satisfies this because the animations closure has no parameters and returns Void, while the completion closure takes a parameter named finished, which is of type Bool, an

A super simple example of adding Objective-C files to a Swift project in Xcode

Getting Started Inside a Swift project select File -> New -> File .. [or cmd + N] Select iOS -> Cocoa Touch Class Provide class name (e.g. HelloSwift), set to Subclass of NSObject and set language to Objective-C Click Next Agree to Bridging Header Navigate to Bridging Header: YourProjectName-Bridging-Header.h Insert the following text into Bridging Header: #import "HelloSwift.h" Adding the code Place the following text in your HelloSwift.h file: #import <Foundation/Foundation.h> @interface HelloSwift : NSObject -(NSString *)helloObjectiveC:(NSString *)name; @end Place this code in your HelloSwift.m file: #import "HelloSwift.h" @implementation HelloSwift -(NSString *)helloObjectiveC:(NSString *)name {     NSString *myString = [NSString stringWithFormat:@"Hello %@, my name is Objective-C", name];     return myString; } @end Inside the viewDidLoad of your initial view controller class file add the following lines of S

A basic struct in iOS (Swift), Windows (C#), and Android (Java)

I'm not going to argue the pros and cons of structs here, I'm simply going to outline the basic code to make use of them across three platforms: iOS, Windows and Android. iOS (Swift) A struct can hold any type of object in Swift. struct Paragraph {     var text:[String]     var level:Int } Implementation is as follows: var myParagraph = Paragraph(text:["This is the first sentence in my paragraph.", "This is the second sentence in my paragraph."], level:1) Access of properties: var paragraphLevel = myParagraph.level Windows (C#) Windows also has a struct type, but the creation of structs in C# is closer to class creation and is less automated than it is in Swift. public struct Paragraph {     public readonly string[] text;     public readonly int level;     public Paragraph(string [] text, int level)    {         this.text = text;         this.level = level;     } } Implementation is as follows: String[] myStrings = {"This

Convenience (or no-arg) initializers (or constructors) in Android (Java), iOS (Swift) and Windows (C# )

The purpose of convenience (or no-arg) initializers is to enable a class to create a class instance with or without parameters being passed to it. Android (Java) public class Trivial { public Trivial() { this(0); } public Trivial(int ctr) { // Do stuff with the int here } } This is referred to as a no-arg constructor in Programming Android . And the fact that it is a no-arg or convenience constructor is implied by the structure. iOS (Swift) class Trivial {  convenience init(){     self.init(ctr: 0)     }     init(ctr:Int) { // Do stuff with the int here     } } In Swift it is explicitly labelled a convenience and this triggers a compiler warning if init() is not called within it. Windows (C#) class Trivial {         public Trivial()             : this(0)         {         }         public Trivial(int ctr)         { // Do stuff with the int here     } } Windows is similar to Android but places the this() call to the constructor outside of the code braces. Fo

Do we have permission to blog about Swift yet?

By in Alcide Dessalines d'Orbigny (Voyage dans l'Amérique méridionale) [Public domain], via Wikimedia Commons Do I have permission to blog about Swift yet? If you're talking about the original Swift  (or the bird) then you shouldn't even be here. Go, get on with your writing. But if as I suspect you are here because you are curious about whether discussing Apple's Swift Programming Language is allowed under Apple's NDA, then you've come to the right place, because I'm curious too. Why has this query arisen? The Swift documentation isn't under the protection of the Apple Developer site, since Apple has already released a free iBook detailing the language. They've also noted the existence of the new language on their main website. In addition to this, Apple have loosened the terms of their NDA, but like Ole Begemann  I'm unclear about the meaning of the term 'public review' in the new NDA terms. Does it apply to tutor