初识 Swift:函数 function

函数(function)是一种可重复使用的代码块,用于执行特定的任务或操作。函数接受输入参数(可选)并返回一个结果(可选),可以通过函数名来调用执行。函数的存在有助于组织和模块化代码,提高代码的可读性、可维护性和可重用性。

Swift 复制代码
func greet(name: String) {
    print("Hello, \(name)!")
}

// 示例用法
greet(name: "Alice")  // 调用函数并传递参数

greet 就是一个函数,调用它其实就是执行 greet 函数内部的代码,打印出一行字符串。print 也是 Swift 内置的函数。

函数练习

Swift 复制代码
print("Row, row, row your boat")
print("Gently down the stream")
print("Merrily, merrily, merrily, merrily")
print("Life is but a dream")
print("        ~        ")
print("Row, row, row your boat")
print("Gently down the stream")
print("If you see a crocodile")
print("Don't forget to scream")
print("        ~        ")
print("Row, row, row your boat")
print("Gently down the stream")
print("This song is quite repetitive")
print("Can you spot the theme")

这是一个童谣的歌词,比如 "Row, row, row your boat" 和 "Gently down the stream" 这两行,重复出现 N 次。试想一个场景,如果出现 100 次,甚至 1000 次的时候,是不是需要重复输入 1000 次,或者当写了 1000 次以后,突然发现里面其中一个单词写错字母了,怎么办,太崩溃了!

这时候,我们就可以把这两行单独整理到一个函数中

go 复制代码
func rowTheBoat() {
    print("Row, row, row your boat")
    print("Gently down the stream")
}

这样,只需要在需要时调用即可。上面的代码既可以调整为:

scss 复制代码
rowTheBoat()
print("Merrily, merrily, merrily, merrily")
print("Life is but a dream")
print("        ~        ")
rowTheBoat()
print("If you see a crocodile")
print("Don't forget to scream")
print("        ~        ")
rowTheBoat()
print("This song is quite repetitive")
print("Can you spot the theme")

以此类推,可以找出类似的重复的代码,整理到不同的函数中,来增加代码的工作量和可阅读性。

相关推荐
YungFan2 小时前
iOS26适配指南之UIViewController
ios·swift
HarderCoder3 天前
我们真的需要 typealias 吗?——一次 Swift 抽象成本的深度剖析
swift
HarderCoder3 天前
ByAI-Swift 6 全览:一份面向实战开发者的新特性速查手册
swift
HarderCoder3 天前
Swift 中 let 与 var 的真正区别:不仅关乎“可变”与否
swift
HarderCoder3 天前
深入理解 Swift 6.2 并发:从默认隔离到@concurrent 的完整指南
swift
麦兜*4 天前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3
HarderCoder5 天前
Swift Concurrency:彻底告别“线程思维”,拥抱 Task 的世界
swift
HarderCoder5 天前
深入理解 Swift 中的 async/await:告别回调地狱,拥抱结构化并发
swift
HarderCoder5 天前
深入理解 SwiftUI 的 ViewBuilder:从隐式语法到自定义容器
swiftui·swift
HarderCoder5 天前
在 async/throwing 场景下优雅地使用 Swift 的 defer 关键字
swift