[Swift / For beginners] Write smartly with type inference

Patterns to apply smartly with type inference

let str:String = "Hello"
let str = "Hello"   
//On the right side"Hello"Is a String type, so str is implicitly a String type
let color:UIColor = UIColor.red
let color:UIColor = .red  
//Since UIColor is explicitly declared on the left side, UIColor on the right side can be omitted.
UIView.animate(withDuration: 1, delay 1, 
options: UIView.AnimationOptions.curveEaseIn, 
animations: { }, completion: nil)

UIView.animate(withDuration: 1, delay 1,
options: .curveEaseIn,
animations: { }, completion: nil)
//Since the argument type is UIView's AnimationOptions, it can be omitted.

Patterns that increase processing costs when written by type inference

(reference) https://t.co/j5Yq9fIrQO?amp=1

let add = (num1 ?? 0 as Int) + (num2 ?? 0 as Int) + (num3 ?? 0 as Int)
//It is faster to specify the type
let add1 = num1 ?? 0 as Int
let add2 = num2 ?? 0 as Int
let add3 = num3 ?? 0 as Int
let sum = add1 + add2 + add3
//It is easier to unwrap it first, or to decompose it for complicated expressions before calculating it.

Recommended Posts

[Swift / For beginners] Write smartly with type inference
Environment construction with Docker for beginners
[Tips] How to solve problems with XCode and Swift for beginners
(For beginners) Swift UI view element collection
Learn Java with "So What" [For beginners]
Write tests for JavaFX applications with TestFX
[Workshop for beginners] Let's write an E2E test with Cloud9 + Docker Compose + Cypress!
[Swift] Perform error handling with Optional <Wrapped> type
Let's easily write multiple loops with swift closure
[For beginners] Test devise user registration with RSpec
Search JPQL for tables with JSON type columns
[Swift] Type type ~ Enumeration type ~
[Swift] Type type ~ Structure ~
[Must-see for beginners] Compile settings with IntellJ [Many images]
[For beginners] Let's be able to coat like Swift!
[Swift] Perform error processing with Result <Success, Failure> type