Here

Elsewhere

sitharus.com

Swift vs C# - My take

Inspired by this comparison of Swift and C# I’ve put together my own list of my favourite features of each language.

My day job is a .NET developer, and I know C# and its pitfalls quite well. I’ve been playing with Swift as soon as it was released.

Throughout these examples I’ll be concentrating on the syntax, I may leave some details unimplemented.

Nulls / Nils

In Swift nil-valued objects are opt-in. You cannot pass a nil unless the function or property allows it.

C# - you’ll get an error at run time
public void DoImportantThings(string cannotBeNull)
{
    if (cannotBeNull == null) 
    {
        throw new InvalidArgumentException(...)
    }
}

public void SillyMethod() 
{
    DoImportantThings(null);
}
Swift - you’ll get an error at compile time
func doImportantThings(string : cannotBeNull) { ... }
func sillyMethod() { doImportantThings(nil) }

This is fantastic! So many errors are caused by unexpected nulls, and that whole set has been eliminated! Next I can hope for a language with built in data validation.

Closures

Lets pick list sorting as an example

C#
myList.Sort((a, b) => a.CompareTo(b))
Swift
myList.Sort { $0 < $1 }

Personally I'm uncertain about Swift's implicit argument names, but I think it'll stick for small functions.

Now say we want to reuse that sorter. Idiomatic C# would break it out in to a method call

private int MySort(int a, int b) 
{
    a.CompareTo(b); 
}
...
myList.Sort(MySort)

or you could use a function variable, but that breaks type inference

Func<int, int, int> mySort = (a, b) => { a.CompareTo(b) }

Swift does a bit better on the second count

let mySort = { (a : Int, b:Int) in a < b }

the return type is inferred, but since Swift lacks automatic generalisation (F#'s reference) it requires type annotations. Given the rest of the functional suite I hope auto generalisation comes to Swift

Data types

C# follows other C-based languages in data types. There are primitive types, functions, classes, structs and enumerations. Functions and closures are first class, which is great, but we're still stuck with the old C/C++/Java ways of grouping things. I won't go in to these here

Swift has a much richer set of types, and coupled with the pattern matching system this leads to better interaction

Tuples

While C# has tuples they're just another class. This makes them somewhat hard to work with, for example C# to return multiple values:

public Tuple<int, int> GetTwoInts() 
{ 
    return Tuple.Create(1, 2); 
}
...
var items = GetTwoInts();
var item1 = items.Item1;
var item2 = items.Item2;

with Swift:

func getTwoInts() -> (int, int) { return (1, 2) }
...
let (item1, item2) = getTwoInts()

Enumerations

In C# enumerations are simply names for integers. They always have a numeric value you can cast from.

Swift's enumerations are really algebraic data types, also known as a tagged union. The values of an enumeration are not an alias for an integer, but a value in their own right. You can assign a number to an enumeration value you can also assign a string or any other value.

For even more power you can assign variable values to enumeration values. For example:

enum socketState {
    Reading(string : buffer)
    Writing(string : buffer)
    Waiting(int : timeout)
}

switch (s : socketState) {
case socketState.Reading(let buffer):
    return .Reading(buffer + readMore())
case socketState.Writing(let buffer):
    return .Writing(write(buffer))
...
}

You can attach any sort of type to an enumeration value. This example also shows off enumeration decomposition to extract values out of the enum - you can also do this with tuples.

Switch statement

While C# lets you switch on constant strings as well as enumerations, Swift lets you match pretty much anything, acting like an if...else if chain, but including decomposition of tuples.

func getHttp(url : string) -> (int : status, string : statusMessage, string : body) {}

switch (getHttp(“…”)) {
    case (404, let message, _) : 
        notFound(message)
    case (403, _, _) : 
        doAuth()
    case (200, _, let body) : 
        processBody(body)
}

While there are other ways of accomplishing this it is easier to manage state machine dispatches like this.

Also instead of C#’s infuriating compulsory break; on each statement and complete inability to fallthrough after doing some work, Swift takes a more pragmatic approach and breaks automatically unless you use the fallthrough keyword.

LINQ

One thing I love about .NET is LINQ, not just the nice operations on lists - which can easily be implemented in Swift - but also the ability to construct expression trees and interpret them at runtime. This allows a fantastic degree of expressiveness, especially when interacting with external systems.

Alas Swift doesn’t have anything like this so far, but with the algebraic data type as a first class member it’s easier to implement a DSL with an alright syntax. Hopefully this will be improved in the future.

Personally I’d like a fully metaprogramming model, macros rather than runtime interpretation.

Extensions

In C# we have extension methods - methods that behave like they’re part of a class, but really are static methods that take an instance as the first parameter.

Swift takes this one step further, extensions can add protocols (similar to a C# interface) to an extant type even without access to the implementation. You can also add computed properties and arbitrary functions. This makes it easy to add other types to your own protocols, and to hide internal mucking around from outside influence.

Visibility

Most languages have a concept of visibility for items - public, protected and private at least. So far Swift doesn’t have these, but it’s early days and I expect them to be implemented in the future.

read

Reddit emoticon text expander Safari extension

Since I’ve been spending more time on reddit I’ve been somewhat annoyed at how some subreddits hide conversations inside emoticon text, mostly because it takes so long to read with all the hovering.

Since Google didn’t bring up any leads, and the Reddit Enhancement Suite didn’t help, I created my own! Though when people find this they’ll probably tell me all about the much better solutions people have already made.

The code was inspired by, but not based on, the (Super Reddit Alt-Text Display)[http://userscripts.org/scripts/show/109869] userscript.

Go from this

reddit-noextn.png

to this!

reddit-withextn.png

So here is the aptly named titletext.safariextz

read

Seal!

There’s been a seal hanging around the Wellington waterfront, and I managed to get this shot of the contented seal face

Seal!

read

LAMP!

So I’ve been moving in to hardware hacking rather than software. I’ve been working in IT software for 8 years now, so something new is fun! Plus if you get hardware wrong you definitely know about it.

First thing I noticed was lighting adequate for software work is useless for tiny hardware work, so I set about building a custom lamp for it.

So, I started with a cheap clip-on desk lamp, and with some components from eBay and a LED pattern laser cut by Ponoko I set to work (pics in full post)

read

CNC, the DIY way

A couple of months ago I decided to do a little DIY air conditioning, more for fun designing circuits and programming microcontrollers. One thing led to another, and now I’m making a mini CNC mill out of spare printer and scanner parts. This will probably take most of the year to complete, but the planning is fun!

read

Chrome dropping h.264, my take.

I’m sure everyone knows that Chrome is dropping h.264 video support for WebM. They claim it will enable “open innovation”. I have a few problems with this.

Firstly, VP8 is probably patented (though it may not be), the algorithms are very similar to the h.264 algorithms, so the MPEG LA may have a claim. Also Google haven’t offered any form of indemnification or analysis to show the patents aren’t infringed. In many cases we’ve seen companies wait for popularity then sue those who can’t defend, one reason GNU doesn’t use GIF.

Secondly, VP8 may be the future, but h.264 is here now. While looking to the future is all well and good, it shouldn’t be at the expense of current usability unless the two are mutually exclusive. The ‘for the future’ argument also falls down with quality comparisons, VP8 and h.264 are of comparable quality, with VP8 falling short at the moment, though that may pick up with more development. VP8 is not a next generation codec, it’s current generation. Arguably VP8 has better peak signal-to-noise ratio (PSNR), but PSNR doesn’t reflect visual quality.

I believe that Google can push WebM in more effective ways. They are working on VP8 hardware acceleration for mobile devices and presumably re-encoding a lot of YouTube content to VP8. I assume they’re also working on WebM support in Flash Player, as once that’s complete non-WebM browsers will have a fallback. All that’s happened in the short term is Chrome users will see h.264 content in Flash Player, rather than in native video, which gives awful playback on Linux. Given Firefox’s performance it seems I’ll be stuck with proprietary browsers if I want performant video playback. Thanks Google.

read

Comic Sans Be Gone does Arial

I’ve pushed a new update to Comic Sans Be Gone. Apart from fixing a minor Javascript issue I’ve added the ability to replace Arial, and to change the replacement font.

Comic Sans Be Gone Settings screenshot

If you have Comic Sans Be Gone installed the check your extensions updates, else grab it

read

Using ApplicationSettings with F#

While F# is a first-class .NET 4 citizen it’s not really a first-class Visual Studio citizen, even in 2010. A lot of the application setup tools we have for C# aren’t present in F#.

I was recently making a quick and dirty tool in F# that needed some basic user settings, so I went with the ApplicationSettings infrastructure in .NET, as it’s the easiest way to implement this. In C# this is easy, the GUI designer writes the code for you. In F# you have to do it yourself. Microsoft’s documentation is in C#, so there’s some adaptation to do.

You’ll need a type that inherits ApplicationSettingsBase class from System.Configuration, and then add some property members with the attribute UserScopedSettingAttribute(). You can also use ApplicationScopedSettingAttribute() for application-level settings, but these require editing the XML in your App.Config, something that I’m not that familiar with yet.

There’s a little boilerplate for each setting, but other than that it’s a breeze.

Here’s a sample settings class:

open System.Configuration
type MySettings() = 
  inherit ApplicationSettingsBase()
  [<UserScopedSettingAttribute()>]
  member this.UserSetting
    with get() = this.Item("UserSetting") :?> string
    and set(value : string) = this.Item("UserSetting") <- value

  [<ApplicationScopedSettingAttribute()>]
  member this.AppSetting
    with get() = this.Item("AppSetting") :?> string

read

EMPing released!

For a fair few months I’ve been working on a nifty app to do notifications for PowerShop products and power balances.

It’s finally released! I present EMPing.

No, it’s not free. Servers aren’t free either and I have to run one to do notifications.

If only I had a million-dollar game idea.

read

Comic Sans Be Gone update

Just a minor update, Comic Sans Be Gone now works on inline styles and FONT tags. Thanks to goblindegook for that.

For Chrome users goblindegook’s Allvetica replaces Arial and optionally Comic Sans with Helvetica.

read