Avoid Long Parameter Lists in Swift

Real-life Problems == Solved

Photo by Etienne Boulanger on Unsplash

Prerequisites:

Keywords and Terminology

The high-level stuff

The problem

The feedback you might receive

Some solutions

Replace a parameter where we can derive the data

let viewWidth = self.view.frame.widthlet sizeRatio = ratio(width: viewWidth, size: .small)
func ratio(size: UserSize) -> CGFloat {
return self.view.frame.width * CGFloat(size.rawValue)
}

Replace

_ = averageHeight(lowValue: 1, highValue: 3, n: 3)
func averageHeight(lowValue: Double, highValue: Double, n: Int) -> Double {
return highValue — lowValue / Double(n)}
}
_ = averageHeight(values: 1,2,3)
func averageHeight(values: Double…) -> Double {
return values.max()! — values.min()! / Double(values.count)
}

Using a data object

func studentScore(name: String, age: Int, testScore: Int, testSubject: String){
print (“\(name): \(age) got \(test) out of 10”)
}

The example

Network managers

A poor initialization process

fetch(url: URL, method: HTTPMethod, headers: [String : String] = [:], token: String? = nil, body: [String: Any], completionBlock: @escaping (Result<Data, Error>)

A better initialization process

func fetch(url: URL, method: HTTPMethod, completionBlock: @escaping (Result<Data, Error>) -> Void)

Conclusion

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store