Swift基础(三):控制流、函数

目录

1.控制流

for in,for,while,if

控制转移语句:continue,break,switch中的 fall through,类似if的guard

2.函数

返回元祖类型,带外部参数,带不定参数,Inout参数,函数类型(类似c语言函数指针),嵌套函数


//1.控制流

// for in

let letInt1 =4;

var letInt2  =5;

for_ in1...letInt1//'_'可以作为忽略项

{

    letInt2+=letInt2;

}

print(letInt2);

let strArray = ["str1","str2","str3"];

for strItemin strArray//for-in遍历数组

{

    print(strItem);

}

let dict1 = [1:"str1",4:"str2"];

for (dictKey,dictVal)in dict1//for-in遍历字典

{

    print(dictKey);

}

//for 循环,类似C语言for

for(var i =0;i<5;i++)

{

    print(i);

}

//while

var varCnt =5;

while(varCnt>0)

{

    varCnt--;

}

varCnt =5;

repeat

{

    varCnt--;

}while(varCnt>0)//repeat while类似do while

//if语句

if(varCnt==0)

{

    print("varcnt==0");

}

//switch大体类似C语言,增加区间case,多个条件时写法与c语言不同

//case为元组

let letArray = (2,3);

switch(letArray)

{

case (1,2):

    print("(1,2)");

    break;

case (0...1,2):

    print("区间匹配");

    break;

case (_,3)://下划线

    print("'_'匹配所有值");

    break;

default:

    print("other!");

    break;

}

//值绑定的方式

let letPt = (4,5);

switch(letPt)

{

case (let x,5):

    print("case (let x,5):\(x),5");

    break;

case (5,let y):

    print("case (5,let y):5,\(y)");

    break;

case (let x,let y):

    print("case (let x,let y):\(x),\(y)");

    break;

}

//where case语句

let letpt1  = (5,9);

switch(letpt1)

{

    caselet (x,y) where x>y:

    print("case let (x,y) where x>y:");

    break;

caselet (x,y) where x<y:

    print("case let (x,y) where x<y:");

    break;

caselet (x,y) where x==y:

    print("case let (x,y) where x==y:");

    break;

default:

    print("other!");

    break;

}


// 控制转移语句

//continue 类似C语言,跳过本次循环进入下次循环

//break:1.循环语句中的break:结束循环,跳到本循环的最后一个}

//break:2.switch中的break:结束switch,跳到本switch的最后一个}

//switch中的fallthrough可实现case语句的贯穿,即:跳到下一个case(因为swiftcase后面不写break,也默认跳出switch)

//swift中允许带标签的语句

//guard 类似if,但是guard必须带一个else,guard要求条件必须为真,否则执行else


//2.函数

func  getStr(name:String)->String//返回string

{

    let letStr ="hello \(name)";

    return letStr;

}

print(getStr("fly"));

func getTwoVal(intval1:Int,intval2:Int)->(Int,Int)//返回两个参数

{

    return (intval1 + intval2,intval1 - intval2);

}

print(getTwoVal(2, intval2:3));//调用

//返回元祖类型

func minMax(array: [Int]) -> (min:Int, max: Int)? {

    if array.isEmpty {return nil }

    var currentMin = array[0]

    var currentMax = array[0]

    for valuein array[1..<array.count] {

        if value < currentMin {

            currentMin = value

        } elseif value > currentMax {

            currentMax = value

        }

    }

    return (currentMin, currentMax)

}

print(minMax([1,2,-5,13,6]));

//带外部参数名的函数:更好的表达参数的意义

func sayHello(to person:String, and anotherPerson: String) -> String

{

    return"Hello \(person) and\(anotherPerson)!"

}

print(sayHello(to:"lw", and: "fly"))

// prints "Hello lw and fly!\n"

//带默认参数的函数

func printVal(parameterWithDefault:Int = 7)

{

    print(parameterWithDefault);

}

printVal(5);// parameterWithDefault is 5

printVal();// parameterWithDefault is 7

//带不定参数的函数

func getSumResult(numbers:Double...) -> Double

{

    var total:Double = 0;

    for numberin numbers

    {

        total += number;

    }

    return total;

}

print(getSumResult(1,2,3,4.5,6.7));


//变量参数

func appendStr(var string:String, totalLength: Int, pad:Character) -> String

{

    string += String(totalLength) + String(pad);

    return string;

}

let originalString ="hello"

let paddedString =appendStr(originalString, totalLength:10, pad: "-")

//输入输出参数

func swapTwoInts(inout a:Int,inout b:Int)

{

    let temporaryA = a;

    a = b;

    b = temporaryA;

}

var varIntOne =4,varIntTwo = 5;

swapTwoInts(&varIntOne, b: &varIntTwo);

print("\(varIntOne),\(varIntTwo)");//print "5,4"


//函数类型:类似c语言的函数指针

func addTwoInts(a:Int, b: Int) ->Int

{

    return a + b;

}

var mathFunction: (Int,Int) -> Int =addTwoInts;

print(mathFunction(2,5));

//函数类型作为参数

func printMathResult(mathFunction: (Int,Int) -> Int, a:Int,  b: Int)

{

    print("Result:\(mathFunction(a, b))");

}

printMathResult(addTwoInts, a:3, b: 5);//print 8

//函数类型作为返回值

func stepForward(input:Int) -> Int

{

    return input +1;

}

func stepBackward(input:Int) -> Int

{

    return input -1;

}

func chooseStepFunction(backwards:Bool) -> (Int) ->Int

{

    return backwards ?stepBackward : stepForward;

}

var currentValue =3

let moveNearerToZero =chooseStepFunction(currentValue >0);

print(moveNearerToZero(4));//print 3

// moveNearerToZero now refers to the stepBackward() function


//嵌套函数:可以在它所在的作用域内被调用

func chooseStepFunctionTwo(backwards:Bool) -> (Int) ->Int

{

    func stepForward(input:Int) -> Int

    {

        return input +1;

    }

    func stepBackward(input:Int) -> Int

    {

        return input -1;

    }

    return backwards ?stepBackward : stepForward;

}

var currentValueTwo = -3;

let moveNearerToZero2 =chooseStepFunctionTwo(currentValueTwo >0);

print(moveNearerToZero2(4));//print 5














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
接着分析 (result (type_ident (component id='Bool' bind=Swift.(file).Bool))) (brace_stmt range=[re.swift:1:59 - line:14:1] (pattern_binding_decl range=[re.swift:2:5 - line:2:33] (pattern_named type='[UInt8]' 'b') Original init: (call_expr type='[UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:33] nothrow (constructor_ref_call_expr type='(String.UTF8View) -> [UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:19] nothrow (declref_expr implicit type='(Array<UInt8>.Type) -> (String.UTF8View) -> Array<UInt8>' location=re.swift:2:19 range=[re.swift:2:19 - line:2:19] decl=Swift.(file).Array extension.init(_:) [with (substitution_map generic_signature=<Element, S where Element == S.Element, S : Sequence> (substitution Element -> UInt8) (substitution S -> String.UTF8View))] function_ref=single) (argument_list implicit (argument (type_expr type='[UInt8].Type' location=re.swift:2:13 range=[re.swift:2:13 - line:2:19] typerepr='[UInt8]')) )) (argument_list (argument (member_ref_expr type='String.UTF8View' location=re.swift:2:29 range=[re.swift:2:21 - line:2:29] decl=Swift.(file).String extension.utf8 (declref_expr type='String' location=re.swift:2:21 range=[re.swift:2:21 - line:2:21] decl=re.(file).check(_:_:).encoded@re.swift:1:14 function_ref=unapplied))) )) Processed init: (call_expr type='[UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:33] nothrow (constructor_ref_call_expr type='(String.UTF8View) -> [UInt8]' location=re.swift:2:19 range=[re.swift:2:13 - line:2:19] nothrow (declref_expr implicit type='(Array<UInt8>.Type) -> (String.UTF8View) -> Array<UInt8>' location=re.swift:2:19 range=[re.swift:2:19 - line:2:19] decl=Swift.(file).Array extension.init(_:) [with (substitution_map generic_signature=<Element, S where Element == S.Element, S : Sequence> (substitution Element -> UInt8) (substitution S -> String.UTF8View))] function_ref=single) (argument_list implicit (argument (type_expr type='[UInt8].Type' location=re.swift:2:13 range=[re.swift:2:13 - line:2:19] typerepr='[UInt8]')) )) (argument_list (argument (member_ref_expr type='String.UTF8View' location=re.swift:2:29 range=[re.swift:2:21 - line:2:29] decl=Swift.(file).String extension.utf8 (declref_expr type='String' location=re.swift:2:21 range=[re.swift:2:21 - line:2:21] decl=re.(file).check(_:_:).encoded@re.swift:1:14 function_ref=unapplied))) ))) (var_decl range=[re.swift:2:9 - line:2:9] "b" type='[UInt8]' interface type='[UInt8]' access=private readImpl=stored writeImpl=stored readWriteImpl=stored)
06-10

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值