Using a do block to provide a limited scope for variables
Thursday, 20 May 2021
When writing a test, sometimes we need to set up a variable with
func test() {
var request1 = URLRequest...
mutate(&request1)
XCTAssert(request1.url.host, "blah")
var request2 = URLRequest...
mutate(&request2)
XCTAssert(request2.url.host, "blah")
}
func test() {
do {
var request = URLRequest...
mutate(&request)
XCTAssert(request.url.host, "blah")
}
do {
var request = URLRequest...
mutate(&request)
XCTAssert(request.url.host, "blah")
}
}
Apart from not having to number our variables, we also make sure we don’t accidently refer to an incorrect request from a previous assertion.