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

推荐订阅源

云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
Recent Announcements
Recent Announcements
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Stack Overflow Blog
Stack Overflow Blog
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
博客园 - 【当耐特】
H
Help Net Security
腾讯CDC
大猫的无限游戏
大猫的无限游戏
GbyAI
GbyAI
Last Week in AI
Last Week in AI
Jina AI
Jina AI
博客园 - 聂微东
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
Y
Y Combinator Blog
C
Check Point 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
Returning Multiple Values from Functions in Swift
Gamya · 2026-06-16 · via DEV Community

When you want to return a single value from a function, you write an arrow and a data type before the opening brace:

func isShinobi(name: String) -> Bool {
    name == "Naruto" || name == "Sasuke" || name == "Sakura"
}

That compares a name against a list of known shinobi names, returning true or false.

But what if you need to return two or more values? Let's explore the options.


🚫 Attempt 1 — Using an Array

Say we want a function that sends back a character's first and last name:

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

let character = getCharacter()
print("Name: \(character[0]) \(character[1])")

This is problematic — it's hard to remember what character[0] and character[1] actually represent. If we ever change the order of the array, character[0] might suddenly become the last name instead of the first, and nothing would warn us.


🚫 Attempt 2 — Using a Dictionary

func getCharacter() -> [String: String] {
    [
        "firstName": "Monkey",
        "lastName": "D. Luffy"
    ]
}

let character = getCharacter()
print("Name: \(character["firstName", default: "Unknown"]) \(character["lastName", default: "Unknown"])")

Now we have meaningful names — firstName and lastName instead of 0 and 1. But look at that print() call: even though we know both keys will exist, Swift doesn't know that, so we still need to provide default values just in case.


✅ Attempt 3 — Using a Tuple

Tuples let us put multiple pieces of data into a single variable, but unlike arrays and dictionaries, tuples have a fixed size and can hold a mix of different types.

func getCharacter() -> (firstName: String, lastName: String) {
    (firstName: "Monkey", lastName: "D. Luffy")
}

let character = getCharacter()
print("Name: \(character.firstName) \(character.lastName)")

Breaking that down:

  • The return type is (firstName: String, lastName: String) — a tuple containing two strings
  • Each value in the tuple has a name, and these aren't in quotes — they're specific labels, not arbitrary dictionary keys
  • Inside the function we send back a tuple matching exactly what we promised
  • When calling getCharacter(), we read the values using .firstName and .lastName

🆚 Tuples vs Dictionaries — What's the Real Difference?

They might look similar, but they behave very differently:

  • With a dictionary, Swift can't know ahead of time whether a key exists. We know character["firstName"] will be there, but Swift doesn't — so we must provide a default value.
  • With a tuple, Swift knows exactly what's available because the tuple's type says so. character.firstName either compiles or it doesn't — there's no chance of a typo like character["First Name"] silently returning nothing.
  • A dictionary could contain hundreds of other keys alongside firstName — a tuple can't. It must contain exactly what its type says, nothing more and nothing less.

💡 Three More Things About Tuples

1. You don't need to repeat the names in return

Since Swift already knows the names from the function's return type, this works exactly the same as the named version above:

func getCharacter() -> (firstName: String, lastName: String) {
    ("Monkey", "D. Luffy")
}

2. Unnamed tuples use numerical indices

If a tuple's elements don't have names, access them with .0, .1, and so on:

func getCharacter() -> (String, String) {
    ("Monkey", "D. Luffy")
}

let character = getCharacter()
print("Name: \(character.0) \(character.1)")

Numerical indices also work on named tuples, but using names is almost always clearer.

3. You can pull a tuple apart into separate constants

Here's the long way — store the tuple, then copy each part out individually:

func getCharacter() -> (firstName: String, lastName: String) {
    (firstName: "Roronoa", lastName: "Zoro")
}

let character = getCharacter()
let firstName = character.firstName
let lastName = character.lastName

print("Name: \(firstName) \(lastName)")

Or skip the middle step entirely and destructure the tuple straight from the function call:

let (firstName, lastName) = getCharacter()
print("Name: \(firstName) \(lastName)")

And if you only need part of the tuple, use _ to ignore the rest:

let (firstName, _) = getCharacter()
print("Name: \(firstName)")


When Should You Use an Array, a Set, or a Tuple? 🤔

Now that we've covered arrays, sets, and tuples individually, here's how to pick the right one. Remember the key differences:

  • Arrays keep order and can have duplicates
  • Sets are unordered and can't have duplicates
  • Tuples have a fixed number of values, each with a fixed type

Here's how that plays out with some examples:

Scenario Best Choice Why
A list of all jutsu names a player has unlocked, where no jutsu can be unlocked twice and order doesn't matter Set No duplicates, order irrelevant
Episodes of a show a user has watched Set or Array Set if you only care whether they watched it; Array if the order watched matters
High scores in a game Array Order matters, and duplicate scores are possible if two players tie
Items on a to-do list Array Predictable order is important
A character's exact stats — say, two integers for strength and speed, plus a Boolean for whether they've unlocked their final form Tuple A fixed number of values with fixed, specific types

Wrap Up 🎬

  • Returning multiple values from a function? Skip arrays and dictionaries — reach for a tuple
  • Tuples give you named, ordered, fixed-type values without the need for default values or string keys
  • Tuple names don't need repeating in return, unnamed tuples use .0, .1, etc., and tuples can be destructured directly into separate constants with let (a, b) = ...
  • When choosing between array, set, and tuple: think about whether order matters, whether duplicates are allowed, and whether you're dealing with a fixed, known number of values