UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.