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

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

相关推荐
大熊猫侯佩2 小时前
拯救发际线行动:用 Swift 和 Image Playground 驾驭 AI 绘图
人工智能·ai·文生图·swift·图生图·imageplayground·apple 智能
linweidong18 小时前
网易ios面试题及参考答案(下)
objective-c·swift·ios开发·切面编程·ios面试·苹果开发·mac开发
大熊猫侯佩1 天前
Swift 迭代三巨头(下集):Sequence、Collection 与 Iterator 深度狂飙
swift·编程语言·apple
大熊猫侯佩1 天前
Swift 迭代三巨头(中集):Sequence、Collection 与 Iterator 深度狂飙
swift·编程语言·apple
大熊猫侯佩1 天前
Swift 迭代三巨头(上集):Sequence、Collection 与 Iterator 深度狂飙
swift·编程语言·apple
1024小神1 天前
xcode多环境 Dev 、Debug 和 Release变量配置以及怎么切换不同环境
开发语言·macos·ios·swiftui·xcode·swift
1024小神2 天前
Swift中跨view视图组件实现全局状态共享的方式汇总
ios·swiftui·swift
Wcowin2 天前
【自荐】OneClip—— 一款简单专业的 macOS 剪贴板管理工具
mac·swift·粘贴板
Sheffi662 天前
Swift 与 OC 混编底层交互原理
ios·objective-c·swift
东坡肘子2 天前
挖掘“沉默的专家” -- 肘子的 Swift 周报 #114
人工智能·swiftui·swift