Swift Tips_Primer-2:字符串,可选型,Arra

2016-05-15  本文已影响0人  cocdog
let str3 = "   ---Hello, Swift!   " as NSString
str3.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " -"))
var errorCode:Int? = 404
errorCode = nil
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"
var emptyArray1:[Int] = []
var emptyArray2:Array<Int> = []
var emptyArray3 = [Int]()
var emptyArray4 = Array<Int>()
//5个0元素的数组
var allZeros = [Int](count: 5, repeatedValue: 0)
for (index,number) in numbers.enumerate(){
    print(index,number)
}
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"]
var dict:Dictionary<String,String> = ["1":"星期一","2":"星期二","3":"星期三","4":"星期四","5":"星期五","6":"星期六","7":"星期日"]
var emptyDict1:[String:Int] = [:]
var emptyDict2:Dictionary <Int,String> = [:]
var emptyDict3 = [String:String]()
var emptyDict4 = Dictionary<Int,Int>()
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)")
}
if let removedWeek = dict.removeValueForKey("1"){
    print("\(removedWeek) 删除成功")
}
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")
func toBinary(var num:Int) -> String{
    var res = " "
    repeat{
        res = String(num%2) + res
        num /= 2
    }while num != 0
    return res
}
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<Int> = []
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)
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<Int> = []
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()
上一篇下一篇

猜你喜欢

热点阅读