Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Apple iOS & macOSApple arbeitet an einem Fitness-Tracker ohne Display(22.09.2026 um 21:33 Uhr)
Apple iOS & macOSApple stoppt Entwicklung des AirTag-großen KI-Pins(22.09.2026 um 22:22 Uhr)
Apple iOS & macOSApple arbeitet an einem Fitness-Tracker ohne Display(22.09.2026 um 21:33 Uhr)
Apple iOS & macOSApple stoppt Entwicklung des AirTag-großen KI-Pins(22.09.2026 um 22:22 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Swift Functions — Returning Values and When to Skip the Return Keyword 📤

In our last article we learned how to create functions and pass data into them. But functions can also send data back — they do some work and return the result. That's what makes them truly powerful. 🧠 📤 Returning Values from F…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

In our last article we learned how to create functions and pass data into them. But functions can also send data back — they do some work and return the result. That's what makes them truly powerful. 🧠









📤 Returning Values from Functions



To return a value from a function you need two things:




  • An arrow -> followed by the data type before the opening brace — telling Swift what type of data will come back

  • The return keyword to actually send the data back



Here's a simple example — rolling a dice:




func rollDice() -> Int {
return Int.random(in: 1...6)
}

let result = rollDice()
print(result)






The -> Int tells Swift "this function will send back an integer". The return keyword sends the actual value back to wherever the function was called.



Now we can call rollDice() anywhere in our app and always get a random number between 1 and 6! If we later want to use a 20-sided dice, we change it once in the function — and every place that calls it automatically gets the new behaviour. ✅




⚠️ Important: When you promise Swift your function returns a value, Swift holds you to it. If you forget to return something your code won't even build — Swift makes sure you always keep your promise!










🔤 A Real Example — Comparing Strings



Let's try something more interesting. Do two strings contain the same letters regardless of order? So "abc" and "cab" should return true because they both have the same letters — just shuffled.



Here's how we can solve it:




func areLettersIdentical(string1: String, string2: String) -> Bool {
let first = string1.sorted()
let second = string2.sorted()
return first == second
}






Breaking it down:




  • Takes two String parameters

  • Returns a Bool — either true or false

  • Sorts both strings alphabetically using .sorted()

  • Compares them — if they match, returns true



So "abc".sorted() becomes "abc" and "cab".sorted() also becomes "abc" — they match! 🎉



We can actually simplify this — skip the temporary constants and compare directly:




func areLettersIdentical(string1: String, string2: String) -> Bool {
return string1.sorted() == string2.sorted()
}






Same result, less code! 🌸









➕ The Pythagorean Theorem



Remember this from school? The hypotenuse of a right-angled triangle equals the square root of the sum of the other two sides squared.



In Swift:




func pythagoras(a: Double, b: Double) -> Double {
let input = a * a + b * b
let root = sqrt(input)
return root
}

let c = pythagoras(a: 3, b: 4)
print(c) // 5.0






Swift has sqrt() built in — we just pass it a number and it gives back the square root. Here:





  • a * a + b * b9 + 1625


  • sqrt(25)5.0









🧹 Skipping the return Keyword



Here's something really clean about Swift — when your function contains only one line of code, you can drop the return keyword entirely:




// With return
func rollDice() -> Int {
return Int.random(in: 1...6)
}

// Without return — exactly the same!
func rollDice() -> Int {
Int.random(in: 1...6)
}






Same for the Pythagorean theorem:




func pythagoras(a: Double, b: Double) -> Double {
sqrt(a * a + b * b)
}






And the letter comparison:




func areLettersIdentical(string1: String, string2: String) -> Bool {
string1.sorted() == string2.sorted()
}






All three do exactly the same thing as before — just cleaner! ✨









🧠 Expressions vs Statements — Why This Works



To understand when you can skip return — you need to know the difference between expressions and statements:



Expressions — code that resolves to a single value:




5 + 8              // resolves to 13
"hello".sorted() // resolves to "aehllo"
Int.random(in: 1...6) // resolves to a number
true && false // resolves to false






Statements — code that performs an action but doesn't become a value:




let name = "Naruto"     // creates a variable — not a value itself
if score > 80 { } // performs a check — not a value itself
for i in 1...10 { } // performs a loop — not a value itself






The rule is simple:




One expression in your function → you can skip return

Statements or multiple lines → you must use return










🔀 if as an Expression



Swift is smart enough to let if act as an expression too — as long as each branch returns a value directly:




// ✅ This works — each branch is a single expression
func greetNinja(name: String) -> String {
if name == "Itachi" {
"The greatest ninja who ever lived."
} else {
"Hello, \(name)!"
}
}






But this doesn't work — because one branch creates a variable instead of returning directly:




// ❌ This doesn't work
func greetNinja(name: String) -> String {
if name == "Itachi" {
"The greatest ninja who ever lived."
} else {
let greeting = "Hello, \(name)!" // ← statement, not expression!
return greeting
}
}






You can even assign the result of an if directly to a constant:




func greetNinja(name: String) -> String {
let response = if name == "Itachi" {
"The greatest ninja who ever lived."
} else {
"Hello, \(name)!"
}
return response
}






This is similar to the ternary operator we learned earlier:




func greetNinja(name: String) -> String {
let response = name == "Itachi" ? "The greatest ninja who ever lived." : "Hello, \(name)!"
return response
}






Both do the same thing — the if version is just more readable for complex conditions! 🌸









🚪 Using return to Exit Early



There's one more use of return worth knowing — even in functions that don't return a value, you can use return by itself to exit the function immediately:




func attemptMission(chakraLevel: Int) {
if chakraLevel < 50 {
print("Not enough chakra! Mission aborted.")
return // exit the function right here!
}

print("Mission starting!")
print("Deploying jutsu...")
print("Mission complete! ✅")
}

attemptMission(chakraLevel: 30)
// prints: Not enough chakra! Mission aborted.

attemptMission(chakraLevel: 80)
// prints: Mission starting! → Deploying jutsu... → Mission complete!






This is called an early return or guard clause — checking conditions at the top and exiting immediately if something isn't right. It keeps your code clean and avoids deeply nested if statements! 💪









🧩 Putting It All Together






// Roll a custom dice
func rollDice(sides: Int) -> Int {
Int.random(in: 1...sides)
}

// Check if ninja names are anagrams
func areNamesAnagrams(name1: String, name2: String) -> Bool {
name1.lowercased().sorted() == name2.lowercased().sorted()
}

// Calculate battle power
func battlePower(attack: Double, defense: Double) -> Double {
sqrt(attack * attack + defense * defense)
}

// Greet based on rank
func greetByRank(name: String, rank: String) -> String {
if rank == "Hokage" {
"Welcome back, Lord \(name)! 🍃"
} else {
"Greetings, \(name) of the \(rank) rank!"
}
}

// Using them all
print(rollDice(sides: 20))
print(areNamesAnagrams(name1: "listen", name2: "silent")) // true
print(battlePower(attack: 3, defense: 4)) // 5.0
print(greetByRank(name: "Naruto", rank: "Hokage"))






Output:




14
true
5.0
Welcome back, Lord Naruto! 🍃












🌟 Wrap Up




  • Use -> Type to tell Swift what your function returns

  • Use return to send the value back

  • When your function has one expression — skip return entirely


  • Expressions resolve to a value — statements perform actions


  • if can act as an expression when each branch returns directly

  • Use return alone to exit a function early even when there's no return value



Return values transform functions from simple code organizers into powerful building blocks that can calculate, compare, and produce results you can use anywhere in your app! 💪



Next up we'll look at returning multiple values using tuples. See you there! 👋

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Swift Functions — Returning Values and When to Skip the Return Keyword 📤

Thematisch verwandte Begriffe: Swift, Functions, Returning, Values · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-82000 | Adobe Experience Manager Forms JEE is affected by a Server-Side Request …
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick