Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If not let - in Swift

Tags:

xcode

macos

swift

is there is a way to negate the "if let" in swift? This looks silly to me:

    if let type = json.type  {      } else {         XCTFail("There is no type in the root element")     } 

I can't use XCTAssertNotNil, because json.type is a enum.

enum JSONDataTypes {     case Object     case Array     case Number     case String } 

Thanks a lot

EDIT: it is a:

var type: JSONDataTypes? = nil 
like image 562
Peter Shaw Avatar asked Dec 10 '14 23:12

Peter Shaw


People also ask

When to use if let and guard let in Swift?

In if let , the defined let variables are available within the scope of that if condition but not in else condition or even below that. In guard let , the defined let variables are not available in the else condition but after that, it's available throughout till the function ends or anything.

What does if let do in Swift?

The “if let” allows us to unwrap optional values safely only when there is a value, and if not, the code block will not run. Simply put, its focus is on the “true” condition when a value exists.

What is the difference between guard let and if let?

With guard let you are creating a new variable that will exist in the current scope. With if let you're only creating a new variable inside the code block.

Can we use if VAR in Swift?

Yes in Swift we have Reference Type when we use a Class and Value Type when we use a Struct , an Enum or a Tuple .


2 Answers

Here's how you do it:

if json.type == nil {   // fail } 
like image 45
Abhi Beckert Avatar answered Sep 23 '22 15:09

Abhi Beckert


Swift 2.0 (Xcode 7) and later have the new guard statement, which sort of works like an "if not let" -- you can conditionally bind a variable in the remainder of the enclosing scope, keeping the "good path" in your code the least-indented.

guard let type = json.type else {     XCTFail("There is no type in the root element") } // do something with `type` here 

The catch to this is that the else clause of a guard must exit that scope (because otherwise you'd fall into code after that clause, where the guarded variables, like type above, are unbound). So it has to end with something like return, break, continue or a function that is known to the compiler to never return (i.e. annotated @noreturn, like abort()... I don't recall offhand if that includes XCTFail, but it should (file a bug if it's not).

For details, see Early Exit in The Swift Programming Language.


As for really-old stuff... There's no negated form of if-let in Swift 1.x. But since you're working with XCTest anyway, you can just make testing the optional part of an assertion expression:

XCTAssert(json.type != nil, "There is no type in the root element") 
like image 106
rickster Avatar answered Sep 22 '22 15:09

rickster