首页 > 代码库 > swift练习(1)

swift练习(1)

最近参照Swift文档 和 http://www.chinaz.com/swift/chapter1/02_a_swift_tour.html的学习整理


//

//  main.swift

//  TestSwift1

//

//  Created by zql on 14-9-10.

//  Copyright (c) 2014 TU. All rights reserved.

//


import Foundation


println("Hello, World!")

println("Hello Swift")


var myVariable = 42

myVariable = 50//var 声明变量 类型编译器自己判定

let myConstant = 42//let 声明常量 类型编译器自己判定


let implicitInteger = 70

let implicitDouble = 70.0

let exPlicitDouble:Double = 70 //如果需要指明变量类型,则如此类写法


//类型转换

let label = "The width is "

let width = 94

let labelWidth = label + String(width)

println(labelWidth) //值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。


//有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠

let apples = 3

let oranges = 5

let appleSummary = "I have \(apples) apples"

let orangeSummary = "I have \(oranges) oranges"

println(appleSummary + "\n" + orangeSummary)


let h = 1.78

let description = "Your h is \(h)"

println(description)


//创建数组和字典

var shopList = ["catfish","water","apple"]//创建数组

shopList[0] = "you and me"//访问数组


 var personInfo = [

    "name":"zhang",

    "age":"24",

]//创建字典


personInfo["name"] = "M"//使用key访问字典

personInfo["sex"] = "nan"//动态添加key-value


let emptyAry = String[]()//创建空数组

let emptyDic = Dictionary<String,Float>()//创建空字典对象


//控制流

let individualScores = [75,43,103,87,12]

var teamScore = 0

//使用for-in循环

for score in individualScores

{

    if score > 50

    {

        teamScore += 3

    }

    else

    {

        teamScore += 1

    }

}

println("The teamScore is \(teamScore)")



/*

if语句中,条件必须是一个布尔表达式——这意味着像if score { ... }这样的代码将报错,而不会隐形地与 0 做对比。


你可以一起使用iflet来处理值缺失的情况。有些变量的值是可选的。一个可选的值可能是一个具体的值或者是nil,表示值缺失。在类型后面加一个问号来标记这个变量的值是可选的。

*/


var optionalString :String? = "Hello" //表示变量值可选

optionalString = nil


var optionalName:String? = "Zhang"

var greeting = "Hello!"


if let nameStr = optionalName   //nameStr 不是nil

{

    greeting = "Hello,\(nameStr)"

}

println(greeting)


optionalName = nil

if let nameStr = optionalName //nameStr 不是nil

{

    greeting = "Hello,\(nameStr)"

}

println(greeting)


/*

    switch支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。

    运行switch中匹配到的子句之后,程序会退出switch语句,并不会继续向下运行,所以不需要在每个子句结尾写break

*/

let vegetable = "red pepper"

switch vegetable

{

    case "celery":

    let vegetabelComment = "Add some raisins and make ants on a log"

    case "cucumber", "watercress":

    let vegetableComment = "That would make a good tea sandwich."

    case let x where x.hasSuffix("pepper"):

    let vegetableComment = "Is it a spicy \(x)?"

    default:

    let vegetableComment = "Everything tastes good in soup."

}


//使用for-in 来遍历字典

let interestingNumbers = [

    "prime":[2,3,4,5,7,11,13],

    "Fibonacci": [1, 1, 2, 3, 5, 8],

    "Square": [1, 4, 9, 16, 25],

]


var largest = 0

for (key,values) in interestingNumbers

{

    for number in values

    {

        if number > largest

        {

            largest = number

        }

    }

}


//使用while and do-while

var n = 2

while n < 100

{

    n = n*2

}


println("n is \(n)")



var m = 2

do

{

    m = m*2

}while m < 100


println("n is \(m)")


//可以在循环中使用..来表示范围,也可以使用传统的写法,两者是等价的   使用..创建的范围不包含上界,如果想包含的话需要使用...

var firstForLoop = 0

for i in 0..3

{

    firstForLoop += i

}

println("firstForLoop is \(firstForLoop)")


var secondForLoop = 0

for var i = 0;i < 3; i++

{

    secondForLoop += i

}


println("secondForLoop is \(secondForLoop)")


//函数和闭包


//使用func来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值

func greet(name:String,day:String)->String

{

    return "Hello \(name),today is \(day)"

}


println(greet("Boob","3"));


//使用一个元组来返回多个值

func getGasPrices()->(Double,Double,Double)

{

    return (3.59,1.78,3.79)

}


println(getGasPrices())


//函数的参数数量是可变的,用一个数组来获取它们

func sumOf(numbers:Int...)->Int

{

    var sum = 0

    for number in numbers

    {

        sum += number

    }

    

    return sum

}


println(sumOf())

println(sumOf(1,2,3))


//函数可以嵌套。被嵌套的函数可以访问外侧函数的变量,你可以使用嵌套函数来重构一个太长或者太复杂的函数。

func returnFifteen()->Int

{

    var y = 10

    func add()

    {

        y += 5

        println("###########")

    }

    

    add()

    println("······###########·····")

    return y

}


returnFifteen()


//函数可以作为另一个函数的返回值。

func makeIncrementer()->(Int->Int)

{

    func addOne(number:Int)->Int{

        return 1+number

    }

    return addOne

}


var increment = makeIncrementer()

increment(7)

println(increment(7))


//函数也可以当做参数传入另一个函数。

func hasAnyMatches(list:Int[],condition:Int->Bool)->Bool

{

    println("······-------·····")

    for item in list

    {

        if condition(item)

        {

            println("······========·····")

            return true

        }

    }

    return false

}


func lessThanTen(number:Int)->Bool

{

    println("······;;;;;;;·····")

    return number<10

}


var number = [20,19,7,29]

hasAnyMatches(number,lessThanTen)



swift练习(1)