惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
U
Unit 42
美团技术团队
NISL@THU
NISL@THU
C
Cisco Blogs
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Cloudbric
Cloudbric
雷峰网
雷峰网
T
Tailwind CSS Blog
博客园 - 司徒正美
The Register - Security
The Register - Security
L
LangChain Blog
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Threat Research - Cisco Blogs
I
InfoQ
S
Schneier on Security
L
Lohrmann on Cybersecurity
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Martin Fowler
Martin Fowler
Schneier on Security
Schneier on Security
F
Fortinet All Blogs
TaoSecurity Blog
TaoSecurity Blog
K
Kaspersky official blog
Google DeepMind News
Google DeepMind News
Cisco Talos Blog
Cisco Talos Blog
PCI Perspectives
PCI Perspectives
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
Project Zero
Project Zero
The GitHub Blog
The GitHub Blog
D
Docker
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Hacker News: Front Page
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
Webroot Blog
Webroot Blog
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Returning Values from Functions in Swift
Gamya · 2026-06-15 · via DEV Community

You've learned how to create functions and pass values into them — but functions can also send data back to wherever they were called from. They do some work, then hand back the result.

Swift has tons of built-in functions that do this. For example sqrt() takes a number and sends back its square root:

let root = sqrt(169)
print(root)
// 13.0

If you want your own functions to send back a value, you need two things:

  1. An arrow (->) followed by a data type before the opening brace — this tells Swift what kind of data will come back.
  2. The return keyword to actually send the value back.

🎲 A Simple Example — Rolling Dice

Imagine you're building a game where characters roll dice. Instead of writing Int.random(in: 1...6) everywhere, you could make it a function:

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

let result = rollDice()
print(result)

-> Int tells Swift this function always sends back an integer, and return is what actually sends it back.

The benefit? If your game later needs a 20-sided dice (say for a D&D style battle), you only change this one function — every place that calls rollDice() automatically uses the new dice. 🎲

Important: If you say a function returns Int, Swift makes sure it always returns an Int. Forget to return something and your code simply won't build.


🌀 A More Complex Example — Comparing Letters

Let's check whether two strings contain the same letters, regardless of order. For example "naruto" and "toruna" should be considered the same because they contain the same letters.

The trick: calling .sorted() on a string returns a new string with the letters in alphabetical order. Sort both strings and compare with ==.

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

Breaking it down:

  • The function accepts two String parameters
  • It returns a Bool — so it must always send back true or false
  • Inside, both strings are sorted and compared

✂️ Shortening the Function — Skipping the Temporary Constants

We don't actually need those first and second constants — we can compare the sorted results directly:

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


🪄 When Can You Skip the return Keyword?

Here's where it gets interesting. Swift lets us drop return entirely — but only in one specific situation: when the function contains a single expression.

Expression vs Statement

This matters because Swift draws a line between two kinds of code:

  • Expression — code that resolves to a single value. Examples: 5 + 8 (becomes 13), "Naruto".count (becomes 6), or greet("Sasuke") (might become "Hello, Sasuke!")
  • Statement — code that performs an action rather than producing a value. Examples: creating a variable (let name = "Otis"), starting a loop, or an if check that runs multiple lines
Code Type Why
5 + 8 Expression Resolves to 13
isAdmin == true OR isOwner == true Expression Resolves to true or false
let name = "Otis" Statement Doesn't produce a value you can return
A multi-line if block with print() calls Statement Performs actions, not a single value

When a function's body is just one expression, Swift already knows that expression is the value to send back — so return becomes optional:

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

Same goes for our dice roller:

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

⚠️ This only works when the function has exactly one line, and that line must directly produce the value you promised to return.


📐 A Third Example — Pythagoras' Theorem

Remember Pythagoras' theorem from school? For a right-angled triangle, the hypotenuse c can be found by squaring both other sides, adding them together, then taking the square root.

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

This can also be boiled down to one line with return removed:

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


🔀 Using if/else Without return

Swift is smart enough to treat if and switch as expressions too — as long as every branch directly produces a value rather than creating new variables.

This is allowed ✅ — both branches directly produce a String:

func greet(name: String) -> String {
    if name == "Madara Uchiha" {
        "Oh wow, the legendary villain!"
    } else {
        "Hello, \(name)"
    }
}

This is not allowed ❌ — the else branch creates a new constant before returning it, making it a statement, not an expression:

func greet(name: String) -> String {
    if name == "Madara Uchiha" {
        "Oh wow, the legendary villain!"
    } else {
        let greeting = "Hello, \(name)"
        return greeting
    }
}


🎯 Assigning an if Result Directly

Because if can act as an expression, Swift even lets you assign its result straight to a constant:

func greet(name: String) -> String {
    let response = if name == "Madara Uchiha" {
        "Oh wow, the legendary villain!"
    } else {
        "Hello, \(name)"
    }

    return response
}

This might look strange at first, but it's basically the same idea as the ternary operator:

func greet(name: String) -> String {
    let response = name == "Madara Uchiha" ? "Oh wow, the legendary villain!" : "Hello, \(name)"
    return response
}


Returning Multiple Values from a Function 🎁

A Swift function can only declare one return type — but that doesn't mean it can only send back one piece of data. There are two common ways to return multiple values:

  1. A tuple, such as (name: String, age: Int)
  2. A collection, such as an array or dictionary

🚫 Attempt 1 — Returning an Array

Let's say we want a function that returns a character's first name and last name. We could try an array:

func getCharacter() -> [String] {
    ["Monkey", "Luffy"]
}

let character = getCharacter()
print(character[0])

This works, but it's risky:

  • What if some cultures write surnames first? Other developers might expect index 0 to be the last name
  • What if we add a middle name later? Everything after it shifts, breaking character[1]

🚫 Attempt 2 — Returning a Dictionary

func getCharacter() -> [String: String] {
    ["first": "Monkey", "last": "Luffy"]
}

let character = getCharacter()
print(character["first"])

Better — now order doesn't matter. But this still has problems:

  • character["First"] (capital F) would silently fail and return nil
  • The dictionary might be missing a key entirely — what if a character like Zoro only goes by one name?
  • Every value comes back as an optional, so we have to unwrap it every time we read it

✅ Attempt 3 — Returning a Tuple

Tuples solve all of this by letting us specify exactly what comes back: each value's name, type, order, and whether it's optional.

func getCharacter() -> (first: String, last: String) {
    (first: "Monkey", last: "Luffy")
}

let character = getCharacter()
print(character.first)
// Monkey

Why this is better:

  • ✅ First name always comes first, last name always second — guaranteed by the function signature
  • ✅ Adding a middle name later won't shift the position of first or last
  • ✅ No case-sensitive string keys to get wrong — character.first either compiles or it doesn't
  • ✅ No optionals — if a character like Zoro only has one name, last would simply be an empty string, not nil

Wrap Up 🎬

  • Use -> Type before a function's opening brace to declare what it returns, and return to send the value back
  • If a function body is a single expression, return can be skipped entirely — this works for plain expressions, and even for if/switch where every branch produces a value directly
  • A statement (like creating a new variable) can't be the thing Swift returns automatically — only expressions can
  • To return multiple values, prefer a tuple over an array or dictionary — it gives you named, ordered, non-optional values that are safer and clearer to work with