Swift 系统学习 14 inout 关键字

本文通过三个实战练习介绍了Swift语言中的函数定义及使用:计算平均数、十进制转二进制及成绩转换。通过这些练习,读者可以更好地理解并掌握Swift语言的基础语法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//: Playground - noun: a place where people can play

import UIKit

// 课堂练习一:
func mean(_ numbers: Double...) -> Double {
    var sum: Double = 0
    // 循环累加
    for number in numbers {
        sum += number
    }
    
    return sum / Double(numbers.count)
}
// 验证:
var meanValue = mean(10.5, 11.345, 2223.21)

// 课堂练习二:
func convertBinary(num: inout Int) -> String {
    var result = ""
    repeat {
        result = String(num%2) + result
        num /= 2
    } while num != 0
    
    return result
}
// 验证
var value = 6
var binaryValue = convertBinary(num: &value)
value // 110

// 课堂练习三:
// 循环修改学生成绩函数
func changeScores(scores: inout [Int], by changeScore: (Int) -> Int) {
    for (index, score) in scores.enumerated() {
        scores[index] = changeScore(score)
    }
}
// 改分方式一:
func changeScoreOne(score: Int) -> Int {
    return Int(sqrt(Double(score)) * 10)
}
// 改分方式二:
func changeScoreTwo(score: Int) -> Int {
    return Int(Double(score) / 150.0 * 100.0)
}
// 改分方式三:
func changeScoreThree(score: Int) -> Int {
    return score + 5
}
// 验证:
var scoreOne = [36, 41, 32, 75, 88, 92]
changeScores(scores: &scoreOne, by: changeScoreOne)
scoreOne

var scoreTwo = [73, 62, 98, 100, 132, 145]
changeScores(scores: &scoreTwo, by: changeScoreTwo)
scoreTwo

var scoreThree = [36, 41, 32, 75, 88, 92]
changeScores(scores: &scoreThree, by: changeScoreThree)
scoreThree

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值