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

SOLVED: New with Swift: a question about Structs

Forums > 100 Days of Swift

I am totally new with Swift...

now I am with the structs... with computed properties...

struct Code {

var language: String 

var containsErrors = false

var report: String {

    if containsErrors {

        return "This \(language) code has bugs!"

    } else {

        return "This looks good to me."

    }
}
}

I can't understand why I have to write "return" in this code... why for example not using "print" instead if I want it to be printed?

if i try with

if containsErrors { print (...) }

it says it must return something... I don't understand why...

the computed property is:

var report: String {...}

where does it say it must return a String ??? the { } in a computed property always mean return ????

doesn't is just say that it must be a string? it doesn't matter if it is printed, or returned,...????

Sorry if it is an obvious question... just starting with all of this...

To return something in a function you must write -> How do I know that it must return something in a computed property ?

Sorry if my english is not very good, because it is not my first language...

Anyway, I will finish my 100 days of switfUi courseeeee!!!!

   

A computed property has a type (String in your case) and always has to return a value of this type. The : String in the declaration means exactly that.

When you just want to print to console you have to use a function instead of a computed property. A function doesn't have to return a value.

func report() {
    if containsErrors {
        print("This \(language) code has bugs!")
    } else {
        print( "This looks good to me.")
    }
}

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.