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

推荐订阅源

GbyAI
GbyAI
WordPress大学
WordPress大学
D
DataBreaches.Net
腾讯CDC
小众软件
小众软件
B
Blog RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Y
Y Combinator Blog
V
V2EX
I
InfoQ
D
Docker
量子位
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
A
About on SuperTechFans
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale 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
Swift Functions — Write Once, Use Everywhere 🔧
Gamya · 2026-06-13 · via DEV Community

Imagine you've written a really useful piece of code and now you need it in 10 different places in your app. Do you copy and paste it 10 times? What if you need to change it later — would you remember to update all 10 copies?

That's exactly the problem functions solve. Write it once, use it everywhere. 🧠


🔧 What Is a Function?

A function is a named chunk of code that you can run whenever and wherever you need it. Instead of repeating the same code over and over, you wrap it up in a function, give it a name, and just call that name whenever you need it.

Here's a simple example — a welcome message for an app:

func showWelcome() {
    print("Welcome to the Ninja Academy! 🍃")
    print("Track your training progress here.")
    print("Set your goals and crush them!")
    print("Let's get started!")
}

Breaking it down:

  • func — tells Swift we're creating a function
  • showWelcome — the name we give it (make it descriptive!)
  • { } — the function body — everything inside runs when the function is called

Now whenever we need that welcome message — we just call it:

showWelcome()

That's called the call site — the place where we call the function. And we can call it as many times as we want, anywhere in our code! ✅


💡 Why Functions Matter

Here's the honest truth about why functions are so important — told through a famous story from programming history:

Dennis Ritchie, the creator of the C programming language, encouraged developers to use lots of small functions by telling everyone that function calls were really cheap. Everyone started writing modular code. Years later they found out function calls were actually expensive — but by then nobody cared, because the code was so much cleaner and easier to maintain! 😄

The lesson? Even when functions had a performance cost — developers preferred them because of how much they improved code quality. Today that cost is essentially gone, and functions are one of the most fundamental tools in any language.


⚙️ Functions with Parameters

Functions become really powerful when you can pass data into them to customize how they work. You've already been using this without realising it:

// isMultiple(of:) is a function that takes a parameter!
number.isMultiple(of: 2)

// random(in:) is a function that takes a parameter!
Int.random(in: 1...20)

We can create our own functions that work the same way. Here's a times table printer:

func printTimesTables(number: Int) {
    for i in 1...12 {
        print("\(i) x \(number) = \(i * number)")
    }
}

printTimesTables(number: 5)

Output:

1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
...
12 x 5 = 60

The number: Int inside the parentheses is called a parameter — it's a placeholder that gets filled in when the function is called. When we write printTimesTables(number: 5) — the 5 is the argument — the actual value we're passing in.

💡 Parameter vs Argument — don't stress about this distinction too much! A parameter is the placeholder in the function definition, an argument is the actual value you pass when calling it. Easy way to remember: Parameter = Placeholder, Argument = Actual value. 😊


📦 Multiple Parameters

Functions can take more than one parameter:

func printTimesTables(number: Int, end: Int) {
    for i in 1...end {
        print("\(i) x \(number) = \(i * number)")
    }
}

printTimesTables(number: 5, end: 20)

Notice how we name each parameter when calling the function — number: 5, end: 20. This is one of Swift's nicest features — you always know exactly what each value means just by reading the call site!

Compare these two:

printTimesTables(number: 5, end: 20)  // ✅ crystal clear
printTimesTables(5, 20)               // ❌ which is which?

Six months from now you'll thank yourself for using named parameters! 🌸

⚠️ Important: Parameters must always be passed in the same order they were defined. This won't work:

printTimesTables(end: 20, number: 5) // ❌ wrong order!

🏗️ When Should You Create a Function?

There are three main situations where functions are the right tool:

1️⃣ When You Need the Same Code in Multiple Places

func showBattleIntro() {
    print("⚔️ Battle starting!")
    print("Prepare your jutsu!")
    print("May the best ninja win!")
}

// Use it at the start of every battle
showBattleIntro()  // round 1
showBattleIntro()  // round 2
showBattleIntro()  // round 3

If you ever want to change the intro — change it once in the function and every battle automatically gets the update! No hunting through your code for every copy. ✅

2️⃣ When You Want to Break Up Long Code

Imagine one massive function doing 200 things — impossible to read! Breaking it into smaller focused functions makes everything cleaner:

func prepareForBattle() { }
func executeBattle() { }
func showBattleResults() { }

Each function has one clear job — easy to read, easy to fix, easy to update. 🌸

3️⃣ Function Composition — Building Big from Small

Swift lets you call functions from inside other functions — building complex behaviour from simple pieces, like Lego bricks! 🧱

func greetNinja(name: String) {
    print("Welcome \(name)!")
}

func startTraining(name: String, jutsu: String) {
    greetNinja(name: name)  // calling another function inside!
    print("Today we practice \(jutsu).")
}

startTraining(name: "Naruto", jutsu: "Rasengan")

Output:

Welcome Naruto!
Today we practice Rasengan.


⚠️ How Many Parameters Is Too Many?

There's no hard rule — but when a function starts taking 6 or more parameters it's worth stopping and asking:

  • Does it really need all of them?
  • Could it be split into smaller functions?
  • Should some of those parameters be grouped together?

In programming this is called a "code smell" — not that the code is wrong, but something about it hints that the structure might need rethinking. A function with too many parameters is often trying to do too much at once! 🧐


🧩 Putting It All Together

Here's a mini ninja training system using everything we covered:

func showAcademyWelcome() {
    print("🍃 Welcome to the Hidden Leaf Academy!")
    print("Train hard and become the best ninja!")
}

func printTrainingSchedule(ninja: String, jutsu: String, days: Int) {
    print("\n📋 Training Schedule for \(ninja):")
    for day in 1...days {
        print("Day \(day): Practice \(jutsu)")
    }
}

func announceGraduation(ninja: String, rank: String) {
    print("\n🎉 Congratulations \(ninja)!")
    print("You have achieved the rank of \(rank)!")
}

// Using all three functions together
showAcademyWelcome()
printTrainingSchedule(ninja: "Naruto", jutsu: "Shadow Clone Jutsu", days: 3)
announceGraduation(ninja: "Naruto", rank: "Genin")

Output:

🍃 Welcome to the Hidden Leaf Academy!
Train hard and become the best ninja!

📋 Training Schedule for Naruto:
Day 1: Practice Shadow Clone Jutsu
Day 2: Practice Shadow Clone Jutsu
Day 3: Practice Shadow Clone Jutsu

🎉 Congratulations Naruto!
You have achieved the rank of Genin!


🌟 Wrap Up

Functions are one of the most important tools in Swift — and in programming in general:

  • func name() { } — defines a function
  • name() — calls a function
  • Parameters let you customize how a function works
  • Arguments are the actual values you pass when calling
  • Always write parameter names when calling — it makes code self documenting
  • Create functions when you need the same code in multiple places
  • Create functions to break up long complex code into readable pieces
  • Watch out for functions with too many parameters — that's a code smell!

And remember — any data you create inside a function is automatically destroyed when the function finishes. It stays contained! 🔒

Next up we'll look at return values — getting data back out of functions. See you there! 👋