WWDC24 SALE: 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.

   

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, 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!

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.