swift系列一:switch、函数

SWITCH

区间匹配,元组匹配

//区间匹配
        let count = 80
        switch count {
        case 0:
            print("none")
        case 1..<10:
            print("<10")
        case 10..<20:
            print(">10")
        case 20...:
            print(">20")
        default:
            break
        }
//元组匹配
        let point = (1,1)
        switch point {
        case (0,0):
            print("原点")
        case (_,0):
            print("在x坐标轴")
        case (0,_):
            print("在y坐标轴")
        case (-2...2,-2...2):
            print("在一个方形区间里")
        default:
            print("其他")
        }

值绑定

//值绑定
        let point = (2,3)
        switch point {
        case (let x,0):
            print("x的值为\(x)")
        case (0,let y):
            print("y的值为\(y)")
        case (let x,let y):
            print("x:\(x),y:\(y)")
        }

where

//where
        let point = (1,-1)
        switch point {
        case let (x,y) where x == y: //let (x,y) 和 (let x,let y) 一个意思
            print("x == y")
        case (let x,let y) where x == -y:
            print("x == -y")
        default:
            print("other")
        }
//where 用于循环中过滤num的值
        var numbers = [10,20,-10,-20,30,-30]
        var sum = 0
        for num in numbers where num > 0 {
            sum += num
        }
        print(sum)

标签语句

//标签语句(给循环起个别名): 可以选择控制内外层的循环continue或者break
        outer: for i in 0...10 {
            for k in 1...4 {
                if k == 3 {
                    continue outer
                }
                if i == 3 {
                    break outer
                }
                print("i == \(i),k == \(k)")
            }
        }

函数 func

  • 形参默认是let,也只能是let

隐式返回

  • 可以省略return
//函数体是一个单一表达式,函数会隐式返回这个表达式
    func sum(v1: Int,v2: Int) -> Int {
        v1 + v2
    }
    
    sum(v1: 10, v2: 20) //30

返回元组:实现多返回值

    func testFunc(a:Int,b:Int) -> (c:Int,d:Int,e:Int) {
        (a+b,a-b,a*b)
    }

函数的文档注释

//快捷键option+command+/
    
    /// 测试的func
    /// - Parameters:
    ///   - a: 参数a
    ///   - b: 参数b
    /// - Returns: 返回值
    func testFunc(a:Int,b:Int) -> (c:Int,d:Int,e:Int) {
        
        (a+b,a-b,a*b)
    }

参数标签

  • 可以修改参数标签,比如at 修改 time
  • 可以用_来省略

    func goToWork(at time: String) {
        print("this time is \(time)")
    }
    goToWork(at: "0930")
    

    func goToWork(_ time: String) {
        print("this time is \(time)")
    }
    goToWork("")

默认参数值

  • 参数可以给一个默认值

    func test1(name:String,age:Int = 10) {
        //
        print("name: \(name),age:\(age)")
    }
    test1(name: "jack") //可以只传name
    test1(name: "rose", age: 18)//也可以都传

可变参数

  • 可以传很多个相同类型的参数(这里也可以直接传一个数组么)
func sum(_ nums: Int...)  {
print("\(nums)")
}
sum(10,20,30,40) //

Print方法

  • print方法的第一个items是一个可变参数Any...
  • 如果有多个参数输出的话,会separator分割开
  • 输出的结尾terminator自带一个换行符
/// - Parameters:
///   - items: Zero or more items to print.
///   - separator: A string to print between each item. The default is a single
///     space (`" "`).
///   - terminator: The string to print after all items have been printed. The
///     default is a newline (`"\n"`).
public func print(_ items: Any..., separator: String = " ", terminator: String = "\n")
  //常规的输出
  print("1","2","3")//1 2 3
  //传分隔符之后的输出
  print("1","2","3",separator:"---")//1---2---3

输入输出参数

  • 可以用inout定义一个输入输出参数:可以在函数的内部修改外部实参的值
  • 可变参数不能标记为inout
  • inout参数不能有默认值(外边传进来的,不可以设置默认值)
  • inout参数的本质是地址传递(引用传递)
  • inout参数不能传let或者字面量(意思就是只能传变量呀,可多次改变的值)
//交换一下两个值
    func swapValues(_ v1: inout Int,_ v2: inout Int) {
        let temp = v1
        v1 = v2
        v2 = temp
    }
    var num1 = 10
    var num2 = 20
    swapValues(&num1, &num2)
    print(num1,num2)
//利用元组来交换一下两个值

    func swapValues(v1: inout Int,v2: inout Int) {
        (v1,v2) = (v2,v1)
    }
    var num1 = 10
    var num2 = 20
    swapValues(v1: &num1, v2: &num2)
    print(num1,num2)

函数重载(是重载不是重写)

  • 重写会关系到继承问题
  • 函数名相同
  • 参数个数不同 || 参数类型不同 || 参数标签不同
  • 注意,重载和返回值无关
  • 还有一种比较容易混淆的,参数默认值
func sum(v1: Int,v2: Int) -> Int {
        v1 + v2
    }
    //参数个数不同
    func sum(v1: Int,v2: Int,v3: Int) -> Int {
        v1 + v2 + v3
    }
    //参数标签不同
    func sum(a v1: Int,b v2: Int) -> Int {
        v1 + v2
    }
    //参数类型不同
    func sum(v1: Int,v2: Double) -> Int {
        v1 + Int(v2)
    }
//这种返回值不同,其他一样的,不是重载,会报错
    func sum(v1: Int,v2: Int) -> Int {
        v1 + v2
    }
    func sum(v1: Int,v2: Int) {
        print(v1,v2)
    }
    //这种写法会有二义性,swift不会报错,会调用sum(v1: Int,v2: Int)
    func sum(v1: Int,v2: Int) -> Int {
        v1 + v2
    }
    func sum(v1: Int,v2: Int,v3: Int = 10) -> Int {
        v1 + v2 + v3
    }

内联函数优化

  • 如果开启了编译器优化,release模式自动开启,编译器会将一些函数展开为函数体
  • 自己理解:swift会将函数的实现直接展开,省略开辟和回收函数空间的操作,提高性能。
  • 不会被内联的函数:1.函数体比较长 2.包含递归调用 3.包含了动态派发
//例如,开始为这样
    func test() {
        print("test")
    }
    test()//函数调用
//内联优化,相当于test()等于print("test")
 print("test")

函数类型

  • 每个函数都是有类型的,函数类型由形参类型、返回值类型组成
func sum(v1: Int,v2: Int) -> Int {
        v1 + v2
    }
let fn: (Int,Int) -> Int = sum(v1:v2:)
        print(fn(1,2))//3

函数类型作为函数参数

类型别名typealias

  • 用来给类型起别名
typealias Byte = Int8
typealias Short = Int16
typealias Long = Int64
  • 也可以给函数类型起别名
//给函数类型起了一个别名IntFunc
typealias IntFunc = (Int,Int) -> Int
        
        func diff(v1:Int,v2:Int) -> Int {
            v1-v2
        }
        //通过别名fn直接传参数调用diff
        let fn: IntFunc = diff(v1:v2:)
        print(fn(20,10))
        //将别名IntFunc类型的参数fn传入setFn方法
        func setFn(_ fn: IntFunc) {
            print(fn(30,11))
        }
        setFn(diff(v1:v2:))
        //将函数类型的别名作为一个返回值类型
        func getFn() -> IntFunc {
            diff(v1:v2:)
        }
        
        let fn2 = getFn()
        print(fn2(3,2))

嵌套函数

  • 将函数定义在函数内部
      func test1(isFirst:Bool) {
            
            func f_func() {
                print("f")
            }
            func s_func() {
                print("s")
            }
            
            return isFirst ? f_func() : s_func()
        }
        test1(isFirst: true)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容