swift学习记录(in)

来源:互联网 发布:维生素vb的作用及功能 编辑:程序博客网 时间:2024/04/30 02:54

in大概有2种用法。

1、for in 

for i in 1..10


2、{arg in 

//to do

}

func hasAnyMatches(list:Array<Int>,condition:Int -> Bool) ->Bool {

   for item in list {

       if condition(item) {

           return true

        }

    }

    returnfalse

}

func lessThanTen(number:Int) ->Bool {

   return number < 10

}

var numbers = [20,19,2,6]

hasAnyMatches(numbers,lessThanTen)

如果要使用hasAnyMatches,而不想把lessThanTen函数明确定义出来,你可以这样:

func hasAnyMatches(list:Array<Int>,condition:Int -> Bool) ->Bool {

    for item in list {

        if condition(item) {

            return true

        }

    }

    return false

}

var numbers = [20,19,2,6]

hasAnyMatches(numbers,{numberin

   return number < 10

})

这不是看起来简洁了很多,因为hasAnyMatches函数中声明了condition函数的参数类型,所以你不需要再声明,可以直接写number 而in用来分隔参数和函数主体。
0 0