Swift is Open Source

DA-LION-619

Honorary Master
Joined
Aug 22, 2009
Messages
13,777
That is pretty sweet. Seems like all the big names are trying to get devs to use their programming stack but making them cross platform!

I've been wanting to learn swift for some time now but am too caught up with my C# and JS. Busy learning to build some Universal Windows Apps.

The thing that caught my eye is being able to create cross platform apps using swift via http://www.elementscompiler.com/elements/silver/. Perhaps mid-2016!

Use Xamarin :p
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Use Xamarin :p
Xamarin's ok if you are a single language programmer who thinks everything can only be done in C#, or Java, ...

The future is statically typed languages with FP and dynamic abilities. Both Java and C# have tried to implement some of this, but with their baggage, the syntax is very ugly and clumsy; similar to block syntax in Objective-C.

As to cross platform support Swift is picking up speed, example: since the open source, we have; working versions on a number of flavors of Linux, BSD unix and more recently Android.

The cross platform foundation library is moving ahead quite fast re a very active community (the largest on github).
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
That is pretty sweet. Seems like all the big names are trying to get devs to use their programming stack but making them cross platform!

I've been wanting to learn swift for some time now but am too caught up with my C# and JS. Busy learning to build some Universal Windows Apps.

The thing that caught my eye is being able to create cross platform apps using swift via http://www.elementscompiler.com/elements/silver/. Perhaps mid-2016!

Btw one of Microsoft's developers is working on getting Visual Studio Code to support Swift,; at the moment the debugger is fully integrated, code completion is still WIP, however until the Swift compiler is ported to Windows, VSCode support will be limited to OSX or linux.

Many other IDEs have however been fully integrated as alternatives to Xcode, example: sublime, vim, textmate, ...

The cross platform foundation library is also moving along quite well, built in Swift with tie backs to the C, C++ core foundation cross platform libraries. This does exclude UIKit and AppKit as these libraries are specific to iOS and OSX, but as I mentioned Swift is fairly easily integrated into Linux's own UI frameworks, same would apply on Android, and ultimately Windows, etc...

If you're wondering why you should consider Swift vs the others. Performance and its adoption of new programming paradigms like FP (functional programming), POP (protocol oriented programming), static typed design, innate avoidance of nil pointers (Optional Type), Generics, Higher Order FP, ...

It already outperforms Objective-C, C, and in most cases aligns well with C++ performance, it's still early days so this is just going to get much better.
FYI C# and Java being JIT languages are far slower. + encumbered with the unpredictability of garbage collection.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
That is pretty sweet. Seems like all the big names are trying to get devs to use their programming stack but making them cross platform!

I've been wanting to learn swift for some time now but am too caught up with my C# and JS. Busy learning to build some Universal Windows Apps.

The thing that caught my eye is being able to create cross platform apps using swift via http://www.elementscompiler.com/elements/silver/. Perhaps mid-2016!

The other thing that might surprise you is that the Swift team are seriously considering making final the default state for all classes. Coming from C#, Java or Objective-c this might surprise or even concern you, but new paradigms like POP, enums and structs that have equivalent functionality to classes mean that you start rethinking the way in which you construct apps. In C# and Java the habit is to build classes and sub class (re OOP). In Swift you might initially adopt that behavior but soon you will see that there are far better / simpler / more power / flexible ways to do things, for example: protocol oriented programming.

As example: none of the Swift apps I built since its launch use OOP in the traditional sense of inheritance and polymorphism.

If you're familiar with using C# interfaces, or Java the concept of protocols (Swift's name for interfaces) should be easy to comprehend, however after a bit you will see that the true power behind Swift protocols is essentially that it provides a far safer way to tackle inheritance without the OOP baggage or the C++ multiple inheritance pains; but the true power lies in its extensibility; or more specifically its ability to provide protocol level generic method implementations for all types that adopt that protocol; and this alone is one of the reasons you will see programmers boasting of huge code reductions when converting from for example: Objective-C to Swift; typical saving is 30 to 40%

One warning though, adopting Swift will take time, in as much the code you will first write will most likely be just a direct translation from your current source, and the savings, performance boosts and easier maintenance is only going to be realized once you've become more experience and re-architected your app.

Here's a write up from a company that tackled this and the benefits they realized in the process:
http://www.sunsetlakesoftware.com/2014/12/02/why-were-rewriting-our-robotics-software-swift
http://www.sunsetlakesoftware.com/2...-rewriting-our-robotic-control-software-swift
 
Last edited:

shauntir

Well-Known Member
Joined
Sep 11, 2013
Messages
457
[)roi(];16777195 said:
The other thing that might surprise you is that the Swift team are seriously considering making final the default state for all classes.
/snip

You've officially piqued my interest!
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
You've officially piqued my interest!

Good, it really is a great project.
Even after 35 years coding, in more than 20 languages, here comes Swift and I can still get excited.

I suggest you look at https://swift.org for more detail.
If you want to track the discussions on evolution (including final) you can look at the list mail archives:
Example: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151221/subject.html

The big difference between this open source language development and any other is the approach that Apple adopted on github.

For example: Although Google says Android is open source, the evolution and development happens all behind closed doors, only once they're content with the new version is it released to the public. If the public wants something to work differently then their only option is to fork the code i.e. maintain a separate project to the Google one.

Apple in comparison is developing live on github, the evolution discussions occur live on the list mail servers, and all bugs are logged and visible on a dedicated jira site for anyone to fix.
Anyone can post an evolution proposal, and there is a healthy debate from a very active community; Apple compiler / foundation / standard library engineers interact around the clock on all topics, plus they're very active on twitter. Let me know if you'd like their twitter accounts.

Btw If you get stuck you simply include them on a tweet and you get solutions tweeted back, simple, friendly back and forth discussion, so unlike the Apple of yesteryear.

There's just so many ways to get involved, from simple typo corrections, to evolution proposals, to bug fixes, to building incomplete functionality, documentation translation, etc.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
One of the key differentiations between Swift and strict OOP languages like C# and Java is it's unique approach to the use of Protocols (Swift name for interfaces / abstract classes).

For example, consider the following composition:

Code:
public abstract class Vehicle
{
    public abstract void Drive();
    public abstract void Reverse();
    public abstract void Honk();
}

So now, when we want to model a Car, we can override their ability to drive, reverse, and honk as appropriate:
Code:
public class Bicycle: Vehicle
{
    public override void Drive()
    {
        // Drive the bicycle forward with pedal power
    }
}

It’s not terrible – At least here we can rely on the default implementation if we just want to give a Bicycle “average” abilities in all areas but driving.

We might prefer that the Bicycle not be required to have any ability to Reverse or Honk, but that’s always the struggle with inheritance-based modeling. You only get to choose one base class to inherit from, and you’re tied to get some behavior that you don’t need, simply because it’s hard to model abstractions using inheritance that avoids giving you more than you need.

Well in Swift you can replicate this behaviour with protocols and as I said initially you might just translate directly like this and it will work, but protocols in Swift are far more flexible than this; for one you're not limited to only inheriting from e.g. 1 base class

So in Swift after a bit more experience you'd would probably model it this way instead:
Code:
protocol Driveable {
    func drive()
}
 
protocol Reversible {
    func reverse()
}
 
protocol Honkable {
    func honk()
}

Then by using Swift's protocol extension we can provide default implementations for each of these abilities, for example:
Code:
extension Drivable {
    func drive() {
        // drive with average speed
    }
}
 
extension Reversible {
    func reverse() {
        // reverse with average speed
    }
}
 
extension Honkable {
    func honk() {
        // emit standard horn sound
    }
}
You would then tie this in using Swift's ability to inherit from multiple protocols (i.e. not limited to a single inheritance like Java or C#).

Code:
struct Porsche: Drivable, Reversible, Honkable {
    func drive() {
        // drive with lightning speed
    }

    // fall back to protocol extension's average reverse speed
    // fall back to protocol extension's average honk sound
}
 
struct Bicycle: Drivable {
    fun drive() {
       // Speed is dependant on the athlete behind the pedals, and the category of Bicycle (maybe that's another protocol type)
    }
}

Things get even more interesting when you apply generics and element conditionals onto the protocol method implementations, as this would allow you to implement single methods that have the adaptability for the different types of structs, classes and enums inheriting these traits (yes even structs and enums can inherit protocols). Oh and when coupled with the functional aspects, this is pure magic.

This style of coding btw is now what's being referring to as POP (protocol orientated programming) i.e. a multiple inheritance paradigm without the nasty side effects of C++ accidental inheritance recursion.
 
Last edited:

Priapus

Honorary Master
Joined
Jun 8, 2008
Messages
11,422
I really wish I had the time to spend digging in two swift and get up and running quickly. Maybe in a few weeks I'll get that. Thanks for the informative posts!
 

_kabal_

Executive Member
Joined
Oct 24, 2005
Messages
5,923
Thanks for posting this, very interesting for somone out of the swift loop?

Why do you need the "protocol" and the "extension"?

This seems very similar to java8 default methods (an method implemented on an interface)
 

shauntir

Well-Known Member
Joined
Sep 11, 2013
Messages
457
[)roi(];16782399 said:
One of the key differentiations between Swift and strict OOP languages like C# and Java is it's unique approach to the use of Protocols (Swift name for interfaces / abstract classes).

/snip

Very interesting. It seems like an easier way to implement the composition pattern. In C# and Java, using composition is preferred over your typical inheritance chain.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
The protocol, just like interfaces and/or abstract classes is to model behaviours or common traits, for example:
The equatable protocol is tied to any type or object than needs to be compared.

The implementation can either be applied directly onto the type / object in question or it can be applied to all the types/ objects inheriting this protocol (you can also make these global protocol implementation behave different depending not he type that is calling them)
Yes this is similar to Java 8's default method, but far more powerful i.e. you can completely avoid OOP + as a bonus the syntax is far easier, including the tagging on of generics.

Here's a simple example, let's say I had the following class:
Code:
public struct Person {
  public let name: String
  public let surname: String
}
To make this comparable, we make the Person struct comply with the equatable protocol which is roughly defined in the standard library like this:
Code:
public protocol Equatable {
    public func ==(lhs: Self, rhs: Self) -> Bool
}
This basically says that in order to conform to Equatable, we have to provide an implementation for the function ==
(side note: this btw is a rudimentary example of how Swift (like C++) can accommodate custom operators, but that's a whole different subject)

Here's how we get the Person struct to adopt the equatable protocol:
Code:
extension Person: Equatable { }

public func ==(lhs: Person, rhs: Person) -> Bool {
    return lhs.name == rhs.name && lhs.surname == rhs.surname
}
Now we can write code like this to check if two types have equal property values:
Code:
if person1 == person2 { }

Any code or framework can typically be extended even ones you don't have code access; i.e. if you were for example using an Ansi ECMA framework which didn't support equatable comparisons, you could extend it in your code to support the equatable protocol and provide your own implementation for the == operator.

All these examples are fairly rudimentary, and only scratch the surface.

Here for example is an extension on Swift Array Type in order to provide an enhanced map behaviour:
Code:
public extension Array {
    public func mapWithIndex<T>(f: (Int, Element) -> T) -> [T] {
        return zip((self.startIndex ..< self.endIndex), self).map(f)
    }
}
This tags on an index reference when mapping array elements, the <T> + T + [T] refers to any type i.e. basic generics .
Here's an example use of this:
Code:
let result = splitInput.mapWithIndex {
    (index, tag) -> Token in
    if index == 0 && !input.hasPrefix(separator) {
        return self.tokenize(tag: tag, separator: separator)
    }
    return Ansi.tokenize(tag: separator + tag, separator: separator)
}
Basically this is a lambda type variable that takes an array, then using mapWithIndex tags on an index reference (zip function re sequence), in order to drop the 1st index if the input prefix is the same as the split separator i.e. to avoid tokenising the starting separator, the returned result is an array of tokenised values.

This might be very confusing re the use of zip and map which are part of the functional programming paradigm i.e. the start of the dreaded monads and applicative functors :sick:

Well I hope I didn't lose you.

So while many features in Swift are present in e.g. Java & C#; their implementations are not so easy in comparison with Swift, Ruby or Haskell + many are limited re inherent design choices. The differences between Swift's design to support optionals (no nil problems) and to simplify the syntax with what is called its syntactic sugar is what makes the use of all of this inherently safe and far easier.

Here's a syntax sugar example:

Let 's say we have an array:
Code:
let myArray = [4, 5, 2, 8, 10, 9, 3]
Now we'd like that sorted, ok, here's a default implementation:
Code:
let reverseMyArray = myArray.sort({ 
    (number1: Int, number2: Int) -> Bool in
    return number1 > number2
})
Whew long winded and easily to forget, just like the old Objective-C block syntax, fortunately Swift has a lot of syntactic sugar.
Here's the above rewritten using the sugar.
Code:
let reverseMyArray = myArray.sort(>)
Basically the compiler not only can infer the type of objects from the array it can also infer that the sort method requires the comparison of two consecutive values, so all you need to say is which way you want the comparison to go.

Hope that helps to answer your question.
 
Last edited:

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Btw in the above I'm using a struct as opposed to a class; so you might wonder why?

In Swift structs and enums are powerful composition structures in their own right.
The key difference between structs and classes is:
  • structs are immutable types
  • classes are mutable types (i.e. pass by reference)

In Java and C# all base types are immutable, yet they never provided you with a true mechanism to model immutable types without the need to worry about integrity during multi threading. Structs are inherently immutable i.e. no special lock/wait/sync code needed to support multi threading.

Structs, classes and enums as I mentioned are fully fledge compositional elements in their own right, meaning they all can contain methods (instance + static), inherit protocols, etc. You'll find one of the most difficult choices when starting out in Swift is deciding which one to use, fortunately its fairly easily to switch between them with minimal code change.

My code after ~1.5 years is averaging about 70% immutable (structs, enums) 30% mutable (classes)

Now the performance worry warts might be concerned about the performance hit that you would take making all your objects immutable i.e. always copy on use, instead pass by reference.

No need to worry, the llvm compiler again does all the magic under the covers, for example if I take a copy of a mutable array (or any object), the compiler under the covers checks if the array memory is at risk of mutation, if not it simply assigns the same memory pointer but its access path is secured as an immutable object. i.e. the only time you really take a hit is if the array you copied is at risk of mutation e.g. multi threaded models :sick:.

Many tests have been done to evaluate this, and as I said before, Swift's speed today is comparable to C and C++, certainly outperforming Objective-C, C# and Java.
 
Last edited:

BandwidthAddict

Expert Member
Joined
Apr 19, 2005
Messages
2,380
Thanks for the overview. Swift looks like a very nice compiled version of Java. BTW, Java 8 has the same kind of interface now.
 

[)roi(]

Executive Member
Joined
Apr 15, 2005
Messages
6,282
Thanks for the overview. Swift looks like a very nice compiled version of Java. BTW, Java 8 has the same kind of interface now.

Thanks I was aware, been using and teaching it for over a year.

There are similarities of course, however adding on functionality is not the same as designing the language around it; so superficially its quite similar, in practice not as flexible.

Another area Java & C# have adapted is Optional data types, which again one could argue but they also have it so its the same as Swift, but you'd be wrong, re in Java & C# Optionals data types are optional i.e. If the programmer chooses not to use it then the language provides no safe guards, and even using it the compiler doesn't force you to resolve all paths i.e. You can still crash trying to access a nil pointer.

In Swift, optionals are innately not optional i.e. you are forced to make a conscious decision about whether a property will be optional or not. The compiler then forces you to initialize all non optional properties i.e. no nil pointers allowed, and for the properties flagged as optional you are required unwrap them before use, again the language has been built to specifically to control this unwrap / wrapping process.

For example: in Java higher functions were added to assist with wrap / unwrap process i.e. map and flatmap, however nothing was done to incorporate unwrapping in the default control processes: if, for, switch, ... meaning the likelihood that it will be adopted is less, in e.g. Swift & Haskell you have no option, as its a key aspect of learning the language.

So whilst we can say Java & C# have optionals and function programming features like higher order functions its not the same as a language designed for that purpose,, and the majority of Java & C# will never use it, analogy of why change when I'm so good at OOP.. There certainly aren't many code examples utilizing this. In Swift that's all you get.
 
Last edited:

_kabal_

Executive Member
Joined
Oct 24, 2005
Messages
5,923
Awesome man, very interesting and cool concepts.

Semi related to this I am currently reading "Learn You a Haskell for Great Good!" for fun
 
Top