LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: error: missing return in global function expected to return 'String

Forums > 100 Days of SwiftUI

https://www.hackingwithswift.com/quick-start/understanding-swift/when-is-the-return-keyword-not-needed-in-a-swift-function#:~:text=func%20greet(name%3A%20String)%20%2D%3E%20String%20%7B%0A%20%20%20%20if%20name%20%3D%3D%20%22Taylor%20Swift%22%20%7B%0A%20%20%20%20%20%20%20%20%22Oh%20wow!%22%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%22Hello%2C%20%5C(name)%22%0A%20%20%20%20%7D%0A%7D

A string is returned directly from both parts of that condition, so it's allowed.

func greet(name: String) -> String {
    if name == "Taylor Swift" {
        "Oh wow!"
    } else {
        "Hello, \(name)"
    }
}

If I use provided code in Xcode playground, it returns below error though the topic says "it is allowed"

error: missing return in global function expected to return 'String'

Why is that?

   

it returns below error though the topic says "it is allowed"
Why is that?

Odd.

I created a new Playgrounds file and tested this code:

// global playground function
// takes in a string and returns a sting
func verifySpell(🧙🏻: String) -> String {
    if 🧙🏻 == "Hermione" {
        "leh-vee-OH-sa"
    } else {
        "You're saying it wrong."
    }
}

// No compiler complaints here...
verifySpell(🧙🏻: "Hermione") // 👈🏼 No errors here...
verifySpell(🧙🏻: "Luna")     // 👈🏼 .. or here!

This worked as advertised. It returns strings, and doesn't complain about not having a return statement.

Keep Coding

I don't know what to tell you.

Try the usual:
(1) Create a new playgrounds file.
(2) Update Xcode and simulators.
(3) Offer burnt toast 🥪 offering to Assemblix, the compiler god.

1      

Thanks it seems my Xcode was stuck in version 14. Updated and problem solved.

   

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 July 28th.

Click to save your free spot now

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.