码迷,mamicode.com
首页 > 编程语言 > 详细

Swift学习-1.基础与函数

时间:2021-06-18 20:12:06      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:bre   rem   判断   amp   parameter   def   integer   int   定义   

主要记录学习swift;学习网址为:https://www.journaldev.com/15163/swift-closure

基础

1.switch-fallthrough

Swift中应用switch时,不再需要使用break结束;如果想继续下个判断,可以用fallthrough结尾。

let x = 5
switch x {
case 0...1:
    print("This is printed for the range 0 to 1 inclusive")
case 2...4:
    print("This is printed for the range 2 to 4 inclusive")
case 5...8:
    print("This is printed for the range 5 to 8 inclusive")
    fallthrough//fallthrough would print the next statements as well
default://The default statement isn‘t needed if the cases cover all the possibilities.But if there is a case not covered then the default statement is a must,else compile time error would occur.
    print("Default is only needed when cases are not exhaustive. Else compile time error will come.")
}
This is printed for the range 5 to 8 inclusive
Default is only needed when cases are not exhaustive. Else compile time error will come.

2.Enumerations

enum MoodType{
    case Happy,Sad,Worried,Tensed,Angry
}
func getMood(mood:MoodType) -> String{//return type can be nil,just appending a ? at the end of it
    if mood == MoodType.Angry {
        return nil
    }else if mood == MoodType.Happy{
        return "Today is your day"
    }
    else{
        return "Something is wrong with your mood today!"
    }
}
print(getMood(mood: .Happy)!)

3.function

函数一般构成:函数标识符+函数名(入参名:入参类型,...) -> 返回类型{}

3.1普通函数无返回类型

func : 函数标识符
display:函数名
websiteName 与 withTutorial:外部参数名(也可称为:参数标签),调用函数时使用;
w 与 t:内部参数,在函数内部使用

func display(websiteName w:String,withTutorial t:String){
    print(w + " " + t)
}
//实现方法
display(websiteName: "www.huihuang.com", withTutorial: "excellent")
//print:www.huihuang.com excellent

3.2省略外部参数函数有返回类型

func sumTwoNumbers(_ a:Int,_ b:Int) -> Int{
    return a+b
}
//实现
sumTwoNumbers(2, 3)
//result : 5

3.3带初始值函数有返回类型

//入参可以设置初始值
//b设置初始值后,调用函数时,可以忽略b,b的值则为2;也可以另传入b的值
func sumTwoNumberWithDefaultValue(_ a:Int,_ b:Int = 2) -> Int{
    return a + b
}
//实现
sumTwoNumberWithDefaultValue(5)//result : 5
sumTwoNumberWithDefaultValue(5, 6)//result : 11

3.4 inout参数函数

//修饰符:inout
//要更改参数的值,使新值即使在函数调用结束后仍保持不变,可以将参数定义为inout。下面的代码片段演示了一个带有此类参数的函数。
//常量不能用作inout参数传入
var i = 3
func increment(_ i :inout Int,by x : Int) -> Int{
    i = i + x
    return i
}

increment(&i, by: 3)
print(i)// result : i = 6

3.5可变参数函数

//可变参数函数
//参数:可以是零个或者更多,参数类型必须说明;每个函数只能存在一个可变参数
func makeSentence(words : String...,other:String) -> String{
    var sentence = ""
    for word in words {
        sentence = sentence + " " + word
    }
    sentence = sentence + other
    return sentence
}

makeSentence(words: "Function","having", "Variadic parameters","Add as many strings here you want", "Can use one variadic parameter per func","Make full use",other:".")
//打印结果:Function having Variadic parameters Add as many strings here you want Can use one variadic parameter per func Make full use."

3.6多个返回值

func returnSentenceAndWordCount(_ strings: String...) -> (sentence: String, wordCount: Int)
{
    var sentence = ""
    for s in strings
    {
        sentence = sentence + " " + s
    }
    return (sentence, strings.count)
}

let data = returnSentenceAndWordCount("Function","returns a tuple", "containing", "sentence and number of strings and word count")

print(data.sentence + "\n\(data.wordCount)")
//打印结果:Function returns a tuple containing sentence and number of strings and word count
4

3.7函数嵌套函数

func sayHello(to name: String) {
    let s = "Hello " + name
    func printString() {
        print(s)
    }
}
sayHello(to: "Anupam") 
//打印结果: Hello Anupam

3.7函数作为类型、参数、返回类型

//平方
func square(_ num : Int) -> Int{
    return num * num
}
square(4)
//立方
func cube(_ num : Int) -> Int{
    return num * num * num
}
cube(4)
//可以将函数,赋值给一个变量或常量,功能和作用与square相同
var exponentialFunction = square
exponentialFunction(4)
//打印结果:16
cube(exponentialFunction(4))
//打印结果:4092

3.8函数作为入参

var integers = [1,2,3,4,5]
func sumOfExponentialsOf(array a: [Int], with function: (Int)->Int)->Int
{
    var result = 0
    for x in a
    {
        result = result + function(x)
    }
    return result
}

sumOfExponentialsOf(array: integers, with: exponentialFunction)
//打印结果:55

3.9函数作为返回

func chooseComputation(isSquared b : Bool) -> (Int)->Int{

    func square(_ num :Int)->Int
    {
        return num*num
    }

    func cube(_ num :Int)->Int
    {
        return num*num*num
    }

    if b {
        return square
    }
    else{
        return cube
    }

}

var result = chooseComputation(isSquared: true)
result(2) 
//打印结果:4
result = chooseComputation(isSquared: false)
result(2) 
//打印结果:8

Swift学习-1.基础与函数

标签:bre   rem   判断   amp   parameter   def   integer   int   定义   

原文地址:https://www.cnblogs.com/PotatoToEgg/p/14900424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!