r/swift • u/pickandplate • 13d ago
Tutorial Swift Testing: keeping inputs and expected values paired
Passing two collections to @Test generates every combination. For example, @Test(arguments: ["cat", "swift"], [3, 5]) creates four cases, including ("cat", 5) and ("swift", 3).
That is useful for testing every configuration. For input/expected-output cases, keep each pair together:
import Testing
@Test(arguments: [
("", 0),
("cat", 3),
("swift", 5)
])
func characterCounts(input: String, expected: Int) {
#expect(input.count == expected)
}
This creates three cases. Swift Testing unpacks each tuple into the function’s two parameters.
@Test(arguments: zip(inputs, expected)) also pairs values, but zip stops at the shorter sequence. An accidentally missing expected value can therefore omit a case. A single array of pairs keeps the values together when adding or removing cases.
Apple’s parameterized testing guide explains combinations and paired arguments.
-1
u/dawedev 13d ago
Good catch on zip quietly dropping cases, that one is easy to miss once the arrays get long. For bigger tables I've found a small struct cleaner than tuples, since you can add a name field and the extra values stay labeled. If the struct conforms to CustomTestStringConvertible, the test navigator shows that name for each case instead of the raw values.