//: Playground - noun: a place where people can play import UIKit // 定义一个数组 var userScores:[Int]? = [12, 990, 572, 3258, 9999, 1024, 666] userScores = userScores ?? [] // 定义一个函数获取数组中最大值和最小值 // 注意: (maxScores:Int, minScores:Int)? 和 (maxScores:Int?, minScores:Int?) 是两个完全不同的表达意思 // 前者表示可选性元组, 后者表示元组中的两个值为可选性,而元组本身不是可选性 func maxminScores(scores:[Int]) -> (maxScores:Int, minScores:Int)? { // 判断传进来的数组是否为空 if scores.isEmpty { return nil } // 获取最大最小值 var curMax = scores[0], curMin = scores[0] for score in scores[1..<scores.count] { curMax = max(curMax, score) curMin = min(curMin, score) } return (curMax, curMin) } if let result = maxminScores(userScores!) { print("The maxScores is \(result.maxScores), the minScores is \(result.minScores)") }