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

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

相关推荐
幸福回头8 小时前
ms-swift 代码推理数据集
llm·swift
不二狗18 小时前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
struggle20252 天前
适用于 iOS 的 开源Ultralytics YOLO:应用程序和 Swift 软件包,用于在您自己的 iOS 应用程序中运行 YOLO
yolo·ios·开源·app·swift
一丝晨光3 天前
数值溢出保护?数值溢出应该是多少?Swift如何让整数计算溢出不抛出异常?类型最大值和最小值?
java·javascript·c++·rust·go·c·swift
Swift社区3 天前
Swift实战:如何优雅地从二叉搜索树中挑出最接近的K个值
开发语言·ios·swift
fydw_7153 天前
大语言模型RLHF训练框架全景解析:OpenRLHF、verl、LLaMA-Factory与SWIFT深度对比
语言模型·swift·llama
文件夹__iOS4 天前
深入浅出 iOS 对象模型:isa 指针 与 Swift Metadata
ios·swift
I烟雨云渊T5 天前
iOS实名认证模块的具体实现过程(swift)
ios·cocoa·swift
Swift社区6 天前
LeetCode 270:在二叉搜索树中寻找最接近的值(Swift 实战解析)
算法·leetcode·swift
I烟雨云渊T6 天前
iOS瀑布流布局的实现(swift)
开发语言·ios·swift