//: Playground - noun: a place where people can play
import UIKit
/*
* 本节主要内容:
* 1.函数的声明和调用(掌握)
* 2.函数和可选型结合(掌握)
* 3.函数和元组结合
* 4.函数的参数标签(理解)
*/
// 一个参数String类型, 没有返回值
func sayHelloTo(name: String) {
print("Say hello to \(name)")
}
sayHelloTo(name: "Jonny")
// 几个没有返回值函数声明
func sayHelloToOne(name: String) -> Void {}
func sayHelloToTwo(name: String) -> () {}
func sayHelloToThree(name: String) {}
// 参数String, 返回String函数
// _下划线是忽略调用函数的参数名部分(没有歧义)
func sayHelloToFour(_ name: String) -> String {
return "Hello to \(name)" // + name
}
let greetings = sayHelloToFour("Bob")
// 和可选型结合: 注意调用函数
// 参数String?, 返回值为String
func sayHelloToFive(name: String?) -> String {
return "Hello to " + (name ?? "Guest")
}
let toName: String? = "Bob"
let helloTo = sayHelloToFive(name: "Bob")
// 没有参数, 返回字符串类型的数组
func sayHelloTo() -> [String] {
return ["Maggie", "Bob", "Kara", "Kim"]
}
var namesArray = sayHelloTo()
// 需求: 给定整型类型的数组, 返回该数组的最大值和最小值(元组)
func findMaxAndMin(numbers: [Int]) -> (max: Int, min: Int)? {
// 没有元素
if numbers.isEmpty {
return nil
}
var minValue = numbers[0]
var maxValue = numbers[0]
for number in numbers {
minValue = min(minValue, number)
maxValue = max(maxValue, number)
}
return (maxValue, minValue)
}
let temp: [Int] = [512, 234, 24534, 2984]
let result = findMaxAndMin(numbers: temp)
//result.max
//result.0
//result.min
let newTemp: [Int] = []
let newResult: (Int, Int)? = findMaxAndMin(numbers: newTemp)
// 函数调用外面处理下面情况: 传数组为nil
var scoreArray: [Int]? = nil
// ??是nil聚合语法
scoreArray = scoreArray ?? []
// 上面这语句已经保证了, 绝对不是nil; 强制解包没有任何风险
// 可选型解包 + 函数调用
if let scoreResult = findMaxAndMin(numbers: scoreArray!) {
// 解包完毕
print("Max is \(scoreResult.max) and min is \(scoreResult.min)")
}
// JSON解析: 创建模型类: NSObject; 包含属性(可选型); 处理服务器返回的某些key没有value的情况
/*
{
"deal_id" : 1234,
"deal_title": "松子料理",
"deal_off":
}
*/
// 给定两个参数String, 返回一个String
func sayHelloTo(_ name: String, greetings: String) -> String {
return "\(greetings), \(name)"
}
// 调用(Swift3.0)
let string = sayHelloTo("Bob", greetings: "Best wishes to")
namesArray.insert("Maggie", at: 2)
func multipy(_ numberOne: Int, _ numberTwo: Int) -> Int {
return numberOne * numberTwo
}
multipy(10, 20)
// 原则: 只要是在没有歧义情况下, 尽量忽略参数名
// Parameter Label: 参数标签
/*
* 内部参数名和外部参数名
* greetings: 内部参数名
* withGreetingWords: 外部参数名
* 目的: 既可以保证外部函数调用的语义明确, 又可以保证函数内部实现的语义明确
*/
func sayHelloToWithLabel(name: String, withGreetingWords greetings: String) -> String {
return "\(greetings), \(name)"
}
// 有参数标签的函数调用
var greeting = sayHelloToWithLabel(name: "Bob", withGreetingWords: "Hello to")
Swift 系统学习 11 函数 函数的声明 和调用 下划线 调用的时候 忽略参数名
最新推荐文章于 2022-01-12 21:01:40 发布