初识 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")

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

相关推荐
烎就是我4 小时前
100行代码swift从零实现一个iOS日历
ios·swift
littleplayer1 天前
iOS 中的 @MainActor 详解
前端·swiftui·swift
躺平每一天1 天前
用 Swift 的高阶函数 reduce 提升代码可读性
swift·掘金·金石计划
风浅月明4 天前
[Swift]pod install成功后运行项目报错问题error: Sandbox: bash(84760) deny(1)
swift
season_zhu4 天前
iOS开发:关于Moya之上的Request层
ios·架构·swift
东坡肘子4 天前
更短的有效期和更长的保质期 | 肘子的 Swift 周报 #080
swiftui·swift·wwdc
风浅月明5 天前
[Swift]Xcode模拟器无法请求http接口问题
http·xcode·swift
season_zhu8 天前
iOS开发:关于URL解析
ios·json·swift
ZRD11128 天前
SwiftUI 表达式
swiftui·swift
一牛9 天前
AppKit 中的响应者链
macos·objective-c·swift