SkillAgentSearch skills...

Mwift

Reflections and experiments with Swift.

Install / Use

/learn @wtaysom/Mwift
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

A Little Swift Review

Two words? Would use.

One more? Willingly.

Welcome to the 21st century. Four years ago LLVM architect Chris Lattner began design on Swift. Conceived with compilation in mind, Swift gears abstractions toward optimization (attention to aliasing, ARC for predictable instance life) and avoids features with performance penalties (pointers, garbage collection, exceptions).

Swift combines the best in modern language thinking with wisdom from the wider Apple engineering culture. The compiler is optimized for performance, and the language is optimized for development, without compromising on either.

So Apple claims. And so it seems after reading The Swift Programming Language. The bar for a better Apple platform language was low. SwiftDevs announce:

Good riddance for Objective-C, whose only good feature was "not as bad as C++".

David Gewirtzis is hopeful:

Swift has the potential to both revolutionize professional app development while at the same time opening the door to more recreational and educational programming.

This dual nature, of both high-performance resultant code and highly interactive development, is something we haven't seen before. If Apple can pull it off effectively, it will be something special.

Back in 2012, in my True confessions of a former iPhone developer, I described Objective-C as "It's a lot like someone welded two separate programming languages together and forgot to grind down the rough edges."

Swift likes rounded corners: conservative syntax, Objective-C object orientation, functional functional programming features. For some:

This is what annoyed me most about the whole Swift presentation. Swift is not in any way shape or form innovative, in terms of language features or design. It is however, another language that aims to be as productive as possible.

Sounds like the perfect Apple product:

Innovation is saying "no" to 1,000 things.

Big Idea Bullets

What makes Swift swift?

  • Conceived for Compilation
  • Safe Syntax
  • Platform Integration

Wat

A Break with legacy permits improved clarity and simplify. What remains baffling?

  • "Immutable" Arrays
  • Implicitly Unwrapped Optional Properties
  • Closure Capture Lists

What else?

Let's take a quick look at the syntax, semantics, especially Automatic Reference Counting, tooling, object orientation, and functional programming.

Syntax

Actually, I'm trying to make Ruby natural, not simple. -- Yukihiro "Matz" Matsumoto

The surface syntax for a programming language serves as its user interface. Syntax makes some constructs easy, others difficult, avoids one class of bugs, enables another. Apple wants Swift's syntax to be clean, conventional, and safe.

Swift is the Helvetica of programming languages. -- John Gruber

In standard Apple style, clean means opinionated. For instance:

Unless you need the specific behavior of i++, it is recommended that you use ++i and --i in all cases, because they have the typical expected behavior of modifying i and returning the result.

Swift aims for a certain kind of neutrality: standard statement/expression dichotomy, limits on error prone combinations, C-style curly braces, Tiger type <T> generics, strong typing with no implicit conversions. You'll learn more about a person from their reaction to Swift's syntax than you will learn about Swift itself:

FWIW: it seems quite verbose to me: in the couple of chapters I've read already, there doesn't seem to be much syntactic sugar. But I suppose verbose means Apple can sell us all bigger monitors :-)

Compare this fellow:

Right now, a lot of Swift code seems like it could be difficult to follow, but we expect that most of it will become second nature with use. Most programmers will likely be happy to take the relatively compressed syntax of Swift, but the language's flexibility may mean that people will end up unintentionally producing perfectly viable code that other Swift users will struggle to read.

I guess when you're used to Objective-C:

UITableView *myTableView = [[UITableView alloc]
	initWithFrame:CGRectZero style:UITableViewStyleGrouped];

Swift is relatively compressed:

let myTableView = UITableView(frame: CGRectZero, style: .Grouped)

A typical method call will be exactly the same length:

[receiver setFlag: flag forKey: key withAttributes: attributes]

just with different punctuation:

receiver.setFlag(flag, forKey: key, withAttributes: attributes)

easier to read than Apple's JavaScript bridge:

receiver.setFlag_forKey_withAttributes(flag, key, attributes)

Anyone can appreciate keyword external parameters after seeing enough obscure many argument method calls. Here's the one I saw yesterday:

problem = Problem.new(
	ai,
	51,
	assignment,
	domain_bids,
	1)

Of course in Ruby you can write:

problem = Problem.new(
	algo_input: ai,
	highest: highest,
	assignment: assignment,
	domain_bids: domain_bids,
	iteration: 1)

However, Ruby hash destructing is a little inconvenient.

Also like Ruby, Swift tends to trade consistency for convenience:

The default behavior of local names and external names is different for functions and methods. ... The default behavior described above mean that method definitions in Swift are written with the same grammatical style as Objective-C, and are called in a natural, expressive way.

Recall that in Ruby, blocks, procs, lambdas, and methods all handle parameters differently. You don't recall? That's because the defaults are basically what you want. Swift tries to do the same. With time we'll see whether Swift's defaults are right.

Swift favors explicit over implicit:

Methods on a subclass that override the superclass's implementation are marked with override -- overriding a method by accident, without override, is detected by the compiler as an error. The compiler also detects methods with override that don't actually override any method in the superclass.

My experience recommends explicit overrides. Swift's most avant garde feature comes with a billion dollar experience recommendation.

Optional Chaining

I call null references my billion-dollar mistake. -- Tony Hoare

C# fixes the mistake by having nullable types:

int? num = null;
if (num.HasValue)
    {
        System.Console.WriteLine("num = " + num.Value);
    }
    else
    {
        System.Console.WriteLine("num = Null");
    }

Swift's does the same more cleanly:

num: Int? = nil

if let value = num {
	println("num = \(value)")
} else {
	println("num = nil")
}

Swift ventures into new territory by allowing chains of possible nulls:

if let johnsStreet = john.residence?.address?.street {
	println("John's street name is \(johnsStreet).")
} else {
	println("Unable to retrieve the address.")
}

The territory is far from virgin. Ruby's underused andand gem accomplishes much the same:

if johnsStreet = john.andand.residence.andand.address.andand.street
	puts "John's street name is #{johnsStreet}."
else
	puts "Unable to retrieve the address."
end

Ultimately inspired by applicative functors in Haskell:

maybe
	(putStrLn "Unable to retrieve the address.")
	(\johnsStreet -> putStrLn "John's street name is " ++ johnsStreet ++ ".")
	(street <$> address <$> residence john)

Haskell may do it all backwards, but to the same effect.

Warts

Bryan Feeney points out a few:

Also why does one use the static modifier with structs and enums, but a syntactically separate but semantically identical class modifier with classes? Why not use the same modifier everywhere?

Yeah, I don't know.

And why is override a keyword when @final is an annotation -- shouldn't they all be annotations? Both can trigger compiler errors.

Well @final is a more rare annotation just like @IBOutlet.

I have one complaint of my own:

The type of a Swift array is written in full as Array<SomeType>, where SomeType is the type that the array is allowed to store. You can also write the type of an array in shorthand form as SomeType[]. Although the two forms are functionally identical, the shorthand form is preferred, and is used throughout this guide when referring to the type of an array. ...

Swift's dictionary type is written as Dictionary<KeyType, ValueType>, where KeyType is the type of value that can be used as a dictionary key, and ValueType is the type of value that the dic

View on GitHub
GitHub Stars12
CategoryDevelopment
Updated3y ago
Forks0

Security Score

60/100

Audited on Jul 23, 2022

No findings