Swift the weird stuff

Scott
Jul 16, 2022

A running list of weird Swift things I encounter.

These are a few ideas for interview questions that explore some of the odd nuances of swift?

What will the following code print?

class Bla {
var closure1: Action?
var closure2: Action?
}
let bla = Bla()
bla.closure1 = {
print("hello 1")
}
bla.closure2 = bla.closure1bla.closure1 = {
print("successful interception")
}
bla.closure2?()

At first it seems as though it might print “successful interception”. However, it actually prints “hello 1”.

class Bla {
var closure1: Action?
var closure2: Action?
}
let bla = Bla()
bla.closure1 = {
print("hello 1")
}
bla.closure2 = {
bla.closure1?()
}
bla.closure1 = {
print("successful interception")
}
bla.closure2?()

It doesn’t seem like this change would do much, but now it prints “successful interception.”

--

--