Swift Tips_Primer-2:字符串,可选型,Array,Dictionary,Set,函数,闭包

  • String类的方法并不如NSString 丰富,所以为了方便,经常要把String 转成NSString ,使用NSString提供的方法方便的处理字符串
let str3 = "   ---Hello, Swift!   " as NSString
str3.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " -"))
  • 在swift中,没有用nil表示,没有就是没有,不是0也不是其他东西,是一种特殊的类型,所以才有了 可选型,表示可以在类型和nil之间选择,虽然可以把一个可选型声明成let,但是一般都声明成var
var errorCode:Int? = 404
errorCode = nil
  • 可选型的三种解包方式
    • 强制解包,使用"!"
    • if let 解包
    • 尝试解包,使用"?"
var errorCode:String? = "404"
//1.
if errorCode != nil {
    "The error code is " + errorCode!
}else{
    "Not error"
}
//2.
if let errorCode = errorCode{
    "The error code is " + errorCode
}
//3.
errorCode?.uppercaseString

  • 可选型,看代码,下面的三种语法结果完全一致
var errorMsg:String? = "Not Found"
let message:String
if let errorMsg = errorMsg{
    message = errorMsg;
}else{
    message = "No Error"
}

let message2 = errorMsg == nil ? "No Error" : errorMsg
let message3 = errorMsg ?? "No Error"
  • 隐式可选型存在的意义:暂时存放一个nil,等用户真正使用的时候给赋值确保不是nil可以直接使用

  • swift 数组的声明

var emptyArray1:[Int] = []
var emptyArray2:Array = []
var emptyArray3 = [Int]()
var emptyArray4 = Array()
//5个0元素的数组
var allZeros = [Int](count: 5, repeatedValue: 0)
  • 遍历一个Array ,既要获取到元素又想获取到下标,可以使用enumerate
for (index,number) in numbers.enumerate(){
    print(index,number)
}
  • Array 的操作,看代码
var array:[String] = ["A","B","C","D","E"]
//增
array.append("F")
array += ["G"]
array += ["H","I"]
array.insert("K", atIndex: 2)
//删
array.removeFirst()
array.removeLast()
array.removeAtIndex(2)
array.removeRange(0..<2)
//改
array[0] = "A"
array[1...3] = ["T","Y","Z"]
array[1..<3] = ["X"]
  • Dictionary 的声明
var dict:Dictionary = ["1":"星期一","2":"星期二","3":"星期三","4":"星期四","5":"星期五","6":"星期六","7":"星期日"]
var emptyDict1:[String:Int] = [:]
var emptyDict2:Dictionary  = [:]
var emptyDict3 = [String:String]()
var emptyDict4 = Dictionary()
  • Dictionary 遍历
Array(dict.keys)
Array(dict.values)
for key in dict.keys{
    print(key)
}
for value in dict.values{
    print(value)
}
for (key,value) in dict{
    print("\(key):\(value)")
}
  • Dictionary 增删改,注意,updateValue 方法和 removeValueForKey方法会返回老的值,方便做一些逻辑处理,而使用索引操作不会返回
if let removedWeek = dict.removeValueForKey("1"){
    print("\(removedWeek) 删除成功")
}
  • Set 提供了很多Array没有的方法,可以很方便的处理集合的交集,并集,子集,真子集,超集,真超集,减法等,效率远高于用NSArray处理
  • 一个函数
func findMinAndMax( numbers:[Int]) -> (max:Int,min:Int)?{
    guard numbers.count > 0 else{
        return nil
    }
    var minValue = numbers[0]
    var maxValue = numbers[0]
    for number in numbers{
        minValue = minValue < number ? minValue : number
        maxValue = maxValue > number ? maxValue : number
    }
    return (maxValue,minValue)
}
var scores : [Int]? = [12,12,13,14,15,43]
scores = scores ?? []
if let result = findMinAndMax(scores!){
    print("maxValue = \(result.max),minValue = \(result.min)")
}
  • 不想定义函数的外部参数名的时候,可以用"_"省略,看代码
func sayHelloTo( name:String, with greeting:String) ->String{
    return "\(name),\(greeting)"
}
sayHelloTo("lindong",with:"Hello")

func sayHelloTo2(name:String,_ greeting:String) ->String{
    return "\(name),\(greeting)"
}
sayHelloTo2("lindong", "Hello")
  • 带有默认值的参数的函数,调用的时候参数的顺序是随意的,不是固定的
func sayHelloTo( name:String, with greeting:String = "Hello") ->String{
    return "\(name),\(greeting)"
}
  • 变长参数
func sayHelloTo2(content greeting:String,names:String ...) -> Void{
    for name in names{
        print( "\(name),\(greeting)")
    }
}
sayHelloTo2(content: "Hello", names: "A","B","C","D")
  • 可变参数--值传递:函数的参数默认是“let”,需要显式的声明为"var"
func toBinary(var num:Int) -> String{
    var res = " "
    repeat{
        res = String(num%2) + res
        num /= 2
    }while num != 0
    return res
}
  • 可变参数--地址传递(引用传递),使用inout关键字,包括Array,Dictionary,Set 等
func swapTwoInts(inout a:Int,inout _ b:Int) {
(a,b) = (b,a)
}
var a:Int = 12
var b:Int = 13
swapTwoInts(&a, &b)
  • 函数变量
func add(a:Int,b:Int) ->Int{
    return a+b
}
let anotherAdd:(Int,Int)->Int = add;
anotherAdd(3,4)
  • 函数变量的用法
var arr:Array = []
for _ in 0..<1000{
    arr.append(random()%1000)
}
//系统默认升序
arr.sort()
//降序
func descendSort(a:Int, _ b:Int)->Bool{
    return a > b
}
arr.sort(descendSort)
//按字母表顺序
func cmpByNumberString(a:Int, _ b:Int)->Bool{
    return String(a) > String(b)
}
arr.sort(cmpByNumberString)
//按离500最近排序
func near500(a:Int, _ b:Int) -> Bool{
    return abs(a - 500) < abs(b - 500) ? true : false
}
arr.sort(near500)
  • 从一个高阶函数到函数式编程的代表:map,filter,reduce
var scores2 = [92,65,66,24,87,75,45]
func changeScores(inout scores:[Int], by changeScore:(Int) -> Int){
    for (index,score) in scores.enumerate(){
        scores[index] = changeScore(score)
    }
}
func changeScore(score:Int) -> Int{
    return Int(sqrt(Double(score) * 10))
}
//changeScores(&scores2, by: changeScore)
//map
scores2.map(changeScore)
//filter
func fail(score:Int) -> Bool{
    return score < 60
}
scores2.filter(fail)
//reduce
func add(num1:Int,num2:Int) -> Int{
    return num1 + num2
}
scores2.reduce(0, combine: add)
scores2.reduce(0, combine: +)
  • 函数作为返回值和函数的嵌套
func step1MailFeeByWeight(weight:Int) ->Int{
    return 1 * weight
}
func step2MailFeeByWeight(weight:Int)->Int{
    return 3 * weight
}
func totalPrice(price:Int,weight:Int) ->Int{
    func chooseMailFeeByWieght(weight:Int)-> (Int) ->Int{
        return weight <= 10 ? step1MailFeeByWeight : step2MailFeeByWeight
    }
    let mailFee = chooseMailFeeByWieght(weight)
    return mailFee(weight) + price * weight
}
  • 闭包:本质上是函数
var arr:Array = []
for _ in 0..<1000{
    arr.append(random()%1000)
}
arr.sort({ (a:Int,b:Int) ->Bool in
    return a > b
})
//语法简化
arr.sort({ (a:Int,b:Int) ->Bool in return a > b })
arr.sort({a,b in return a > b})
arr.sort({a,b in  a > b})
arr.sort({$0 > $1})
arr.sort(>)
//Trailing Closure,如果闭包是最后一个参数,可以把闭包提到外面
arr.sort(){ a , b in
    return a > b
}
//没有其他参数,小括号可以省略
arr.sort{ a , b in
    return a > b
}
//闭包练习:转为二进制字符串
arr.map{(var number) -> String in
    var res = ""
    repeat{
        res = String(number % 2) + res
        number /= 2
    }while number != 0
    return res
}
  • 闭包和函数属于引用类型
func runningMetersPreDay(mPerDay:Int) -> ()->Int{
    var totalMeters = 0
    return {
        totalMeters += mPerDay
        return totalMeters
    }
}
var planA = runningMetersPreDay(1000)
planA()
planA()
var planB = runningMetersPreDay(2000)
planB()
planB()
var anotherPlan = planB
anotherPlan()
planB()

你可能感兴趣的:(Swift Tips_Primer-2:字符串,可选型,Array,Dictionary,Set,函数,闭包)