Swift — Type inference for stored properties

Arshad
2 min readMar 26, 2021

--

When using the stored property we have different ways to initalize it.

Lets take an example for Int Array.

a) var a = [Int]()

b) var b = [Int] : []

c) var c = [Int] : [Int]()

d) var d= Array<Int>()

e) var e: [Int] = Array()

f) var f: [Int] = .init()

g) var g= [] as [Int]

Lot of them might be using option “a” as this is what is mentioned swift.org

Lets see what is mentioned in Apple website

So if we see Apple don't recommend the option “a”

Type inference for stored properties has 2 points to remember

  1. one compiler efficiency.

2. When you infer a type the compiler must evaluate the expression on the right. For stored properties, this means callers need to compile that expression, just to get the type.

Type inference is an amazing feature in Swift but we need to remember the trade off for it. Using in projects that can latter come as killing for the compiler.

Let me know in comments which ones you prefer?

References

--

--

Arshad
Arshad

Written by Arshad

Mobile enthusiastic, iOS developer.

No responses yet