mistercake
mistercake

Reputation: 723

Preconditions in Swift and Testing Them

In Java I can use frameworks like Guava to check method preconditions, for example like this:

public void doSomething(int index) {
  Preconditions.checkArgument(index >= 3);
  // do something
}

And I can then test them like this:

@Test(expected = IllegalArgumentException.class)
public void testDoSomething() {
  sut.doSomething(2);
}

How can I do the same thing in Swift?

I know about Swift's assertions, but I don't know how you would test for them.

Upvotes: 0

Views: 765

Answers (1)

Christian
Christian

Reputation: 22343

You also can use preconditions in Swift by using precondition. Like that:

func test(hello:String){
    precondition(hello == "Hello", "String is Hello")

}

For example, in the Swift REPL:

> test("Hello")
> test("Hellox")
precondition failed: String is Hello: file /var/folders/z3/kd0nj4ln1rgcpm8bdz7067wh0000gs/T/./lldb/566/repl1.swift, line 2
Execution interrupted. Enter Swift code to recover and continue.

Upvotes: 1

Related Questions