Behind-the scenes improvements in Swift 4.1

Slava Pestov
Apr 11, 2018 · 18 min read

Special declaration names

Bridging peephole

let result = myObj.someMethod(with: arg) as NSArray

Definite initialization improvements

let x: String
if y < 0 {
x = "hello"
} else {
x = "goodbye"
}
print(x)
let x: String
if y >= 0 {
x = "ok"
}
print(x)
class OnlineDocument {
let title: String
let contents: String

init(title: String, from url: URL) throws {
self.title = title
self.contents = try OnlineDocument.load(from: url)
try validate()
}
static func load(from url: URL) throws { ... } func validate() throws { ... }
}

Parent pointer removal from type metadata

class Horse {
struct Saddle {}
}
struct SkipList<T> : Sequence {
func makeIterator() -> Iterator { return Iterator(self) }
struct Iterator : Swift.Iterator {
let list: SkipList<T> // we can reference T here
func next() -> T { ... } // ...and here
}
}
func iterate<I : Iterator>(_ iter: Iterator) { ... }iterate(mySkipList.makeIterator())
class Outer : Outer.Inner {
class Inner { ... }
}

Classes conforming to protocols with default implementations

protocol Widget {
func print()
func clone() -> Self
}
extension Widget {
func print() { print("a widget of type \(Self.self)")
func clone() -> Self { return self }
}
class Box<Element> : Widget {
let contents: T
// Default implementation of print() is OK! // You must define this, or conformance checking fails:
func clone() -> Self { return self }
}
class Crate<T> : Box<T> {}let c = Crate<Int>(value: 3)
c.print()
// prints: a widget of type Box<Int>

Merge modules pass and serialized SIL

Lazier declaration checking in single-file mode

// File 1
class C1 : C2 { ... }
// File 2
class C2 : C3 { ... }
// File 3
class C3 : C4 { ... }
// File 4
class C4 { ... }
// File 1
class MyClass : BaseClass {
func method1(a: NSObject) { ... very complex code ... }
func method2(b: UIView) { ... very complex code ... }
override func method3(c: SomeOtherClass) { ... very complex code ... }
}
// File 2
public func callMethodOnClass(m: MyClass) {
b.method2()
}
// File 3
public func storeClass(m: MyClass) {
someArray.append(m)
}

Removal of -sil-serialize-all mode

Conclusion

Slava Pestov

Written by

Swift compiler hacker; http://twitter.com/slava_pestov

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade