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

推荐订阅源

宝玉的分享
宝玉的分享
Know Your Adversary
Know Your Adversary
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
Cloudbric
Cloudbric
Scott Helme
Scott Helme
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
P
Privacy International News Feed
S
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
S
Security @ Cisco Blogs
N
News | PayPal Newsroom
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
AI
AI
MyScale Blog
MyScale Blog
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
AWS News Blog
AWS News Blog
Webroot Blog
Webroot Blog
C
Cisco Blogs
博客园 - 聂微东
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
D
DataBreaches.Net
博客园_首页
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Project Zero
Project Zero
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
V2EX - 技术
V2EX - 技术
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
V
V2EX
I
Intezer
美团技术团队
TaoSecurity Blog
TaoSecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
G
GRAHAM CLULEY

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
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! 👋