Swift from a C# developer's point of view

I'm thinking I might a bit of a language nut. Or maybe it's the fact that I made a half-assed attempt at Objective-C back in the day, but never could get past the barrier of brackets. In either case, Swift doesn't look half-bad. It has many of the nice features that I'm used to from .NET, including generics, while getting rid of a lot of cruft from Objective-C, including separate header and implementation files and at-declarations (@property(nonatomic copy retain)); all-in-all making the coding on iOS and Mac a lot more approachable from a variety of languages, including C#, Java and JavaScript. Listening to podcasts about the language, you quickly get to the realization that the language and tooling is still maturing (read: changing), so learning and writing about it is volatile at the moment. That said, let's ... have a Swift conversation, shall we? For starters, there's var - which works like var in C# - and let - which works like let in F#. And there's type inference and a relaxed views on semi-colons:
var x = 3 // I'm an variable Int! let y = "Hello World" // I'm a constant String! If you need to specify the type, you do it after the identifier: var xpos : CGFloat = 3 Optional values are basically nullable ones: var maybeButton: UIButton? // Can be a button or nil (Swift's null) To check if an optional value contains anything, you use a if var/let construct: if var actualButton = maybeButton { // Yep, there's a button there } Then, there are functions, which works like methods in C#, but has some special attributes to them: func myMethod(publicName privateName: parameterType) -> returnType { /* method body */ } An example would be: func calculateNextPosition(lastPosition: CGPoint, inout state usingState: CGFloat) -> CGPoint { ... } A call to this method would look like this: var pos = calculateNextPosition(currentPos, usingState: &xpos) Inside the function, the second parameter is called state, but from the outside, we project it as usingState (to make the call more sentence like). Oh, and inout is the equivalent of C#'s ref. To pass an inout parameter, you use the address-of operator - &. If we combine optional variables with functions, we can write code like the following if myRect = updateRect(myRect) { // myRect was updated! Do something exciting with it } else { // Same old myRect. } Let's see ... what else have I fiddled with thus far... There's the slightly different array syntax and its accompanying dictionary syntax: var myArray = [String] // Array of Strings var myDictionary = [String: Int] // Dictionary of String to Int Which brings us to loops! The for-in loops works like foreach, but Swift has a couple of range operators: for index in 1...3 { /* Loop from 1 to 3 inclusive */ } for anotherIndex in 0..<10 { /* Loop from 0 to 9 */ } If you want to loop through dictionaries, you extract the key-value pair into a tuple: for (animalName, legCount) in ["spider": 8, "ant": 6, "cat": 4] { println("\(animalName)s have \(legCount) legs") } Swift has string interpolation. Sweet, eh? Enums are slightly different, sporting associated values: enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) } In this example, ripped directly from the Swift docs, we define an enumeration called Barcode which can take either a value of UPCA with an associated value of a tuple of (Int, Int, Int, Int), or we can take a value of QRCode with an associated value of String. You could create a value like this: var productBarcode = Barcode.UPCA(8, 12353, 8383, 4) ... and then modify it with a shorthand ... productBarcode = .QRCode("IASHFOIA") ... since the Swift compiler at that stage knows that productBarcode is of type Barcode and thus supports its enumeration members. To test for enumeration values, Swift's switch statement is mighty powerful: switch productBarcode { case .UPCA(let system, let manufacturer, let product, let check): println("UPC-A: \(system), \(manufacturer), \(product), \(check).") case .QRCode(let productCode): println("QR Code: \(productCode).") } As can be seen above, the switch statement allows you not only to match on enumeration types, but also extract its associated values (as constants in this case). Oh, and cases don't fall through, so there's no break to be sprinkled all over the place. Oh, right ... I mentioned generics in the beginning. Generics feels like generics in C#, but you put the restrictions by the type rather than in a separate contextual where clause: func doubleCheckThat<T: Equatable>(lhs thisValue: T, rhs isLargerThan: T) -> Bool { return lhs > rhs } Swift is close enough to C# that it's highly readable and at the same time injects some fun new ideas. I spent some time this summer reading Apple's book on it's Swift programming language and found the language guide easy to read with many easy-to-follow examples. I recommend the book to .NET developers on all levels curious on this new language.

Comments

Popular posts from this blog

Auto Mapper and Record Types - will they blend?

Unit testing your Azure functions - part 2: Queues and Blobs

Testing WCF services with user credentials and binary endpoints