swift

头像
erDuo
    阅读 10 分钟

    //2015.03.06
    //赋值运算符
    var b = 10
    var a = 5
    a = b
    // a 现在等于 10
    let (x, y) = (1, 2)
    // 现在 x 等于 1, y 等于 2

    //算术运算符
    //加法(+)
    //减法(-)
    //乘法(*)
    //除法(/)

    //求余运算符
    //求余运算(a % b)是计算b的多少倍刚刚好可以容入a,返回多出来的那部分(余数)
    9 % 4 // 等于 1
    //在对负数b求余时,b的符号会被忽略。这意味着 a % b 和 a % -b的结果是相同的

    //浮点数求余计算
    8 % 2.5 // 等于 0.5

    //自增和自减运算
    //当++前置的时候,先自増再返回。
    //当++后置的时候,先返回再自增。
    a = 0
    b = ++a // a 和 b 现在都是 1
    let c = a++ // a 现在 2, 但 c 是 a 自增前的值 1

    //除非你需要使用i++的特性,不然推荐你使用++i和--i,因为先修改后返回这样的行为更符合我们的逻辑。

    //一元负号运算符
    let three = 3
    let minusThree = -three // minusThree 等于 -3
    let plusThree = -minusThree // plusThree 等于 3, 或 "负负3"

    //一元正号运算符

    //复合赋值(Compound Assignment Operators)
    a = 1
    a += 2 // a 现在是 3

    //比较运算符
    //等于(a == b)
    //不等于(a != b)
    //大于(a > b)
    //小于(a < b)
    //大于等于(a >= b)
    //小于等于(a <= b)
    //等===和不恒等!==

    //三目运算符(Ternary Conditional Operator)
    //问题 ? 答案1 : 答案2

    //空合运算符(Nil Coalescing Operator)(a ?? b)
    //空合运算符(a ?? b)将对可选类型a进行空判断,如果a包含一个值就进行解封,否则就返回一个默认值b.这个运算符有两个条件:

    //表达式a必须是Optional类型
    //默认值b的类型必须要和a存储值的类型保持一致
    //空合并运算符是对以下代码的简短表达方法
    //a != nil ? a! : b
    //注意: 如果a为非空值(non-nil),那么值b将不会被估值。这也就是所谓的短路求值。

    let defaultColorName = "red"
    var userDefinedColorName:String? //默认值为nil
    var colorNameToUse = userDefinedColorName ?? defaultColorName
    //userDefinedColorName的值为空 ,所以colorNameToUse的值为red

    userDefinedColorName = "green"
    colorNameToUse = userDefinedColorName ?? defaultColorName
    //userDefinedColorName非空,因此colorNameToUsede的值为绿色

    //区间运算符
    //闭区间运算符(a...b)
    for index in 1...5 {
    println("(index) * 5 = (index * 5)")
    }
    //半开区间运算符(a..<b)
    let names = ["Anna", "Alex", "Brian", "Jack"]
    let count = names.count
    for i in 0..<count {
    println("第 (i + 1) 个人叫 (names[i])")
    }

    //逻辑运算
    //逻辑非(!a)
    //逻辑与(a && b)
    //逻辑或(a || b)

    //字符串和字符(Strings and Characters)
    //字符串字面量(String Literals)

    //初始化空字符串 (Initializing an Empty String)
    var emptyString = "" // 空字符串字面量
    var anotherEmptyString = String() // 初始化 String 实例
    // 两个字符串均为空并等价。
    if emptyString.isEmpty {
    println("什么都没有")
    }
    // 打印输出:"什么都没有"

    //字符串可变性 (String Mutability)

    //字符串是值类型(Strings Are Value Types)
    //Swift 的String类型是值类型。 如果您创建了一个新的字符串,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。 任何情况下,都会对已有字符串值创建新副本,并对该新副本进行传递或赋值操作。

    //使用字符(Working with Characters)
    for character in "Dog!??" {
    println(character)
    }
    let yenSign: Character = "¥"

    //计算字符数量 (Counting Characters)
    let unusualMenagerie = "Koala ??, Snail ??, Penguin ??, Dromedary ??"
    println("unusualMenagerie has (countElements(unusualMenagerie)) characters")
    // 打印输出:"unusualMenagerie has 40 characters"

    //连接字符串和字符 (Concatenating Strings and Characters)
    let string1 = "hello"
    let string2 = " there"
    var welcome = string1+string2

    // welcome 现在等于 "hello there"
    var instruction = "look over"
    instruction += string2
    // instruction 现在等于 "look over there"
    let exclamationMark: Character = "!"
    welcome.append(exclamationMark)
    // welcome 现在等于 "hello there!"

    //字符串插值 (String Interpolation)
    let multiplier = 3
    let message = "(multiplier) 乘以 2.5 是 (Double(multiplier) * 2.5)"
    // message 是 "3 乘以 2.5 是 7.5"

    //比较字符串 (Comparing Strings)
    //Swift 提供了三种方式来比较字符串的值:字符串相等、前缀相等和后缀相等。
    //字符串相等 (String Equality)
    let quotation = "我们是一样一样滴."
    let sameQuotation = "我们是一样一样滴."
    if quotation == sameQuotation {
    println("这两个字符串被认为是相同的")
    }
    // 打印输出:"这两个字符串被认为是相同的"

    //前缀/后缀相等 (Prefix and Suffix Equality)(hasPrefix/hasSuffix)
    let romeoAndJuliet = [
    "Act 1 Scene 1: Verona, A public place",
    "Act 1 Scene 2: Capulet's mansion",
    "Act 1 Scene 3: A room in Capulet's mansion",
    "Act 1 Scene 4: A street outside Capulet's mansion",
    "Act 1 Scene 5: The Great Hall in Capulet's mansion",
    "Act 2 Scene 1: Outside Capulet's mansion",
    "Act 2 Scene 2: Capulet's orchard",
    "Act 2 Scene 3: Outside Friar Lawrence's cell",
    "Act 2 Scene 4: A street in Verona",
    "Act 2 Scene 5: Capulet's mansion",
    "Act 2 Scene 6: Friar Lawrence's cell"
    ]
    var act1SceneCount = 0
    for scene in romeoAndJuliet {
    if scene.hasPrefix("Act 1 ") {
    ++act1SceneCount
    }
    }
    println("There are (act1SceneCount) scenes in Act 1")
    // 打印输出:"There are 5 scenes in Act 1"

    /*
    var mansionCount = 0
    var cellCount = 0
    for scene in romeoAndJuliet {
    if scene.hasSuffix("Capulet's mansion") {
    ++mansionCount
    } else if scene.hasSuffix("Friar Lawrence's cell") {
    ++cellCount
    }
    }
    */

    println("(mansionCount) mansion scenes; (cellCount) cell scenes")
    // 打印输出:"6 mansion scenes; 2 cell scenes"
    //大写和小写字符串(Uppercase and Lowercase Strings)
    //import Foundation
    let normal = "Could you help me, please?"
    //let shouty = normal.uppercaseString
    // shouty 值为 "COULD YOU HELP ME, PLEASE?"
    //let whispered = normal.lowercaseString
    // whispered 值为 "could you help me, please?"

    //Unicode???
    //Unicode 术语(Unicode Terminology)

    //集合类型 (Collection Types)
    //数组
    //数组的简单语法
    //Array
    //[SomeType]
    //数组构造语句
    var shoppingList: [String] = ["Eggs", "Milk"]
    // shoppingList 已经被构造并且拥有两个初始项。
    var shoppingList1 = ["Eggs", "Milk"]

    //访问和修改数组
    println("The shopping list contains (shoppingList.count) items.")
    // 输出"The shopping list contains 2 items."(这个数组有2个项)
    if shoppingList.isEmpty {
    println("The shopping list is empty.")
    } else {
    println("The shopping list is not empty.")
    }
    // 打印 "The shopping list is not empty."(shoppinglist不是空的)
    shoppingList.append("Flour")
    // shoppingList 现在有3个数据项,有人在摊煎饼
    shoppingList += ["Baking Powder"]
    // shoppingList 现在有四项了
    shoppingList += ["Chocolate Spread","Cheese","Butter"]
    // shoppingList 现在有七项了
    shoppingList[0] = "Six eggs"
    // 其中的第一项现在是 "Six eggs" 而不是 "Eggs"
    shoppingList[4...6] = ["Bananas", "Apples"]
    // shoppingList 现在有六项
    shoppingList.insert("Maple Syrup", atIndex: 0)
    // shoppingList 现在有7项
    // "Maple Syrup" 现在是这个列表中的第一项
    let mapleSyrup = shoppingList.removeAtIndex(0)
    // 索引值为0的数据项被移除
    // shoppingList 现在只有6项,而且不包括Maple Syrup
    // mapleSyrup常量的值等于被移除数据项的值 "Maple Syrup"
    let firstItem = shoppingList[0]
    // firstItem 现在等于 "Six eggs"
    let apples = shoppingList.removeLast()
    // 数组的最后一项被移除了
    // shoppingList现在只有5项,不包括cheese
    // apples 常量的值现在等于"Apples" 字符串

    //数组的遍历
    for item in shoppingList {
    println(item)
    }

    //enumerate(shoppingList)???
    for (index, value) in enumerate(shoppingList) {
    println("Item (index + 1): (value)")
    }

    //创建并且构造一个数组
    var someInts = Int
    println("someInts is of type [Int] with (someInts.count) items。")
    // 打印 "someInts is of type [Int] with 0 items。"(someInts是0数据项的Int[]数组)

    someInts.append(3)
    // someInts 现在包含一个INT值
    someInts = []
    // someInts 现在是空数组,但是仍然是[Int]类型的。

    var threeDoubles = [Double](count: 3, repeatedValue:0.0)
    // threeDoubles 是一种 [Double]数组, 等于 [0.0, 0.0, 0.0]

    var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
    // anotherThreeDoubles is inferred as [Double], and equals [2.5, 2.5, 2.5]

    var sixDoubles = threeDoubles + anotherThreeDoubles
    // sixDoubles 被推断为 [Double], 等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

    //字典
    //Dictionary<KeyType, ValueType>

    //字典字面量
    //[key 1: value 1, key 2: value 2, key 3: value 3]
    var airports: [String:String] = ["TYO": "Tokyo", "DUB": "Dublin"]
    var airports1 = ["TYO": "Tokyo", "DUB": "Dublin"]

    //读取和修改字典
    println("The dictionary of airports contains (airports.count) items.")
    // 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)

    if airports.isEmpty {
    println("The airports dictionary is empty.")
    } else {
    println("The airports dictionary is not empty.")
    }
    // 打印 "The airports dictionary is not empty.(这个字典不为空)"

    airports["LHR"] = "London"
    // airports 字典现在有三个数据项
    airports["LHR"] = "London Heathrow"
    // "LHR"对应的值 被改为 "London Heathrow

    //作为另一种下标方法,字典的updateValue(forKey:)方法可以设置或者更新特定键对应的值。就像上面所示的示例,updateValue(forKey:)方法在这个键不存在对应值的时候设置值或者在存在时更新已存在的值。和上面的下标方法不一样,这个方法返回更新值之前的原值。这样方便我们检查更新是否成功。

    if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB") {
    println("The old value for DUB was (oldValue).")
    }
    // 输出 "The old value for DUB was Dublin."(DUB原值是dublin)

    if let airportName = airports["DUB"] {
    println("The name of the airport is (airportName).")
    } else {
    println("That airport is not in the airports dictionary.")
    }
    // 打印 "The name of the airport is Dublin Internation."(机场的名字是都柏林国际)

    //用下标语法来通过给某个键的对应值赋值为nil来从字典里移除一个键值对
    airports["APL"] = "Apple Internation"
    // "Apple Internation"不是真的 APL机场, 删除它
    airports["APL"] = nil
    // APL现在被移除了

    if let removedValue = airports.removeValueForKey("DUB") {
    println("The removed airport's name is (removedValue).")
    } else {
    println("The airports dictionary does not contain a value for DUB.")
    }
    // prints "The removed airport's name is Dublin International."

    //字典遍历
    for (airportCode, airportName) in airports {
    println("(airportCode): (airportName)")
    }
    // TYO: Tokyo
    // LHR: London Heathrow

    for airportCode in airports.keys {
    println("Airport code: (airportCode)")
    }
    // Airport code: TYO
    // Airport code: LHR

    for airportName in airports.values {
    println("Airport name: (airportName)")
    }
    // Airport name: Tokyo
    // Airport name: London Heathrow

    let airportCodes = Array(airports.keys)
    // airportCodes is ["TYO", "LHR"]

    let airportNames = Array(airports.values)
    // airportNames is ["Tokyo", "London Heathrow"]

    //创建一个空字典
    var namesOfIntegers = Dictionary<Int, String>()
    // namesOfIntegers 是一个空的 Dictionary<Int, String>
    namesOfIntegers[16] = "sixteen"
    // namesOfIntegers 现在包含一个键值对
    namesOfIntegers = [:]
    // namesOfIntegers 又成为了一个 Int, String类型的空字典

    //集合的可变性
    //不可变性对数组来说有一点不同,当然我们不能试着改变任何不可变数组的大小,但是我们可以重新设定相对现存索引所对应的值。
    //注意:
    //在我们不需要改变数组大小的时候创建不可变数组是很好的习惯。如此 Swift 编译器可以优化我们创建的集合。

    //控制流
    //For 循环
    //For-In
    for index in 1...5 {
    println("(index) times 5 is (index * 5)")
    }

    let base = 3
    let power = 10
    var answer = 1
    for _ in 1...power {
    answer *= base
    }
    println("(base) to the power of (power) is (answer)")
    // 输出 "3 to the power of 10 is 59049"

    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names {
    println("Hello, (name)!")
    }

    let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
    for (animalName, legCount) in numberOfLegs {
    println("(animalName)s have (legCount) legs")
    }

    for character in "Hello" {
    println(character)
    }

    //For条件递增(for-condition-increment)
    for var index = 0; index < 3; ++index {
    println("index is (index)")
    }
    // index is 0
    // index is 1
    // index is 2

    //for initialization; condition; increment {
    //statements
    //}

    var index: Int
    for index = 0; index < 3; ++index {
    println("index is (index)")
    }
    // index is 0
    // index is 1
    // index is 2
    println("The loop statements were executed (index) times")
    // 输出 "The loop statements were executed 3 times

    //While 循环
    //While
    let finalSquare = 25
    var board = [Int](count: finalSquare + 1, repeatedValue: 0)
    board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
    board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08

    var square = 0
    var diceRoll = 0
    while square < finalSquare {
    // 掷骰子
    if ++diceRoll == 7 { diceRoll = 1 }
    // 根据点数移动
    square += diceRoll
    if square < board.count {
    // 如果玩家还在棋盘上,顺着梯子爬上去或者顺着蛇滑下去
    square += board[square]
    }
    }
    println("Game over!")

    //Do-While
    do {
    // 顺着梯子爬上去或者顺着蛇滑下去
    square += board[square]
    // 掷骰子
    if ++diceRoll == 7 { diceRoll = 1 }
    // 根据点数移动
    square += diceRoll
    } while square < finalSquare
    println("Game over!")

    //条件语句


    erDuo
    5 声望0 粉丝

    triple Hits:what,why and How