BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 30 - Couldn't understand one specific line of code, needs some explanation

Forums > 100 Days of SwiftUI

On Day 30, we have created a function called isOriginal(). I don't understand the statement inside the body. Actually, what I don't understand is what a logical NOT operator (!) before an array (usedWords) means. The code is as follows:

func isOriginal(word: String) -> Bool {
        !usedWords.contains(word)
}

Can anyone please explain it to me? Thank you.

3      

Hi @banglapp

The function pass in a String word then contains(word) see is the word is in the usedWords array would return true. The ! will return true if the word is NOT in the array.

Nigel

4      

its called reverse logic or negative logic. instead of testing something to be true you are testing something to be false.

in your function it could be written like this

if contains.usedword(whatever){ return} else{ do something special }

if you need to do something only if the function doesnt return true then you can eliminate the if block and leave else block cos thats what you are interested in.

as you cant use else block by itself then you are checking whatever is in else block i.e. do something only if the function returns false.

if !function_returning_true{ do something special}

I was struggling with understanding negative logic back when i started C programming but after getting the concept i was using mostly negative logic in my code.

4      

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.