{"action":"created","issue":{"url":"https://api.github.com/repos/aliencode/aliencode.github.io/issues/1","labels_url":"https://api.github.com/repos/aliencode/aliencode.github.io/issues/1/labels{/name}","comments_url":"https://api.github.com/repos/aliencode/aliencode.github.io/issues/1/comments","events_url":"https://api.github.com/repos/aliencode/aliencode.github.io/issues/1/events","html_url":"https://github.com/aliencode/aliencode.github.io/issues/1","id":52327251,"number":1,"title":"swift基础.md","user":{"login":"aliencode","id":2787688,"avatar_url":"https://avatars.githubusercontent.com/u/2787688?v=3","gravatar_id":"","url":"https://api.github.com/users/aliencode","html_url":"https://github.com/aliencode","followers_url":"https://api.github.com/users/aliencode/followers","following_url":"https://api.github.com/users/aliencode/following{/other_user}","gists_url":"https://api.github.com/users/aliencode/gists{/gist_id}","starred_url":"https://api.github.com/users/aliencode/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/aliencode/subscriptions","organizations_url":"https://api.github.com/users/aliencode/orgs","repos_url":"https://api.github.com/users/aliencode/repos","events_url":"https://api.github.com/users/aliencode/events{/privacy}","received_events_url":"https://api.github.com/users/aliencode/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/aliencode/aliencode.github.io/labels/IOS","name":"IOS","color":"eb6420"}],"state":"open","locked":false,"assignee":null,"milestone":null,"comments":2,"created_at":"2014-12-18T05:32:35Z","updated_at":"2015-02-10T03:00:04Z","closed_at":null,"body":"## 检查类型\r\n\r\n用类型检查操作符(is)来检查一个实例是否属于特定子类型，返回 true 或 false 。\r\n\r\n\r\n## 申明变量\r\n\r\n```swift\r\nvar aaa = 1 //很长的数值可以用 _ 来分隔，如 111_222.1 = 111222.1\r\n```\r\n\r\n根据值判断变量类型\r\n\r\n## 字符输出\r\n\r\n```swift\r\nprintln( \"hello \\(aaa) !\" );\r\n```\r\n\r\n`aaa` 将被值替换.\r\n\r\n## 字符串合并\r\n\r\n```swift\r\nvar b = \"aaa:\" + String(a)\r\n```\r\n\r\n## 数组\r\n\r\n```swift\r\nvar shoppingList = [\"catfish\", \"water\", \"tulips\", \"blue paint\"]\r\n\r\n\r\n//key/value 形式\r\n\r\nvar occupations = [\r\n    \"Malcolm\": \"Captain\",\r\n    \"Kaylee\": \"Mechanic\",\r\n]\r\n\r\noccupations[\"Jayne\"] = \"Public Relations\"\r\n```\r\n\r\n### 申明空数组\r\n\r\n```swift\r\nlet emptyArray = [String]()\r\nlet anyArray = [Any]() //表示任意数据类型的数组\r\nlet emptyDictionary = [String: Float]()\r\n```\r\n\r\n用switch来判断读取anyArray数据\r\n```swift\r\nfor thing in things {\r\n    switch thing {\r\n    case 0 as Int:\r\n        println(\"zero as an Int\")\r\n    case 0 as Double:\r\n        println(\"zero as a Double\")\r\n    case let someInt as Int:\r\n        println(\"an integer value of \\(someInt)\")\r\n    case let someDouble as Double where someDouble > 0:\r\n        println(\"a positive double value of \\(someDouble)\")\r\n    case is Double:\r\n        println(\"some other double value that I don't want to print\")\r\n    case let someString as String:\r\n        println(\"a string value of \\\"\\(someString)\\\"\")\r\n    case let (x, y) as (Double, Double):\r\n        println(\"an (x, y) point at \\(x), \\(y)\")\r\n    case let movie as Movie:\r\n        println(\"a movie called '\\(movie.name)', dir. \\(movie.director)\")\r\n    default:\r\n        println(\"something else\")\r\n    }\r\n}\r\n```\r\n\r\n## for-in使用\r\n\r\n```swift\r\nlet individualScores = [75, 43, 103, 87, 12]\r\nvar teamScore = 0\r\nfor score in individualScores {\r\n    if score > 50 {\r\n        teamScore += 3\r\n    } else {\r\n        teamScore += 1\r\n    }\r\n}\r\n```\r\n\r\n### key/value形式遍历\r\n\r\n```swift\r\nlet interestingNumbers = [\r\n    \"Prime\": [2, 3, 5, 7, 11, 13],\r\n    \"Fibonacci\": [1, 1, 2, 3, 5, 8],\r\n    \"Square\": [1, 4, 9, 16, 25],\r\n]\r\nvar largest = 0\r\nfor (kind, numbers) in interestingNumbers {\r\n    for number in numbers {\r\n        if number > largest {\r\n            largest = number\r\n        }\r\n    }\r\n}\r\n```\r\n\r\n\r\n## if-else使用\r\n\r\n```swift\r\nvar optionalString = \"World\" \r\n\r\nvar optionalName: String? = \"John Appleseed\"  //申明变量为的值为可选的，不然 optionalName = nil 会报错\r\noptionalName = nil\r\n\r\nvar greeting = \"Hello!\"\r\n\r\nif let name = optionalName {  //如果 optionalName 不为 nil 则name将被赋值，不然跳过下面的代码块到else代码块。\r\n    greeting = \"Hello, \\(name)\"\r\n}else\r\n{\r\n    greeting = \"Hello, \\(optionalString)\"\r\n}\r\n\r\n```\r\n\r\n## switch使用\r\n\r\n```swift\r\nvar vegetableComment=\"\"\r\n\r\nlet vegetable = \"red pepper\"\r\nswitch vegetable {\r\ncase \"celery\":\r\n     vegetableComment = \"Add some raisins and make ants on a log.\"\r\ncase \"cucumber\", \"watercress\":\r\n     vegetableComment = \"That would make a good tea sandwich.\"\r\ncase let x where x.hasSuffix(\"pepper\"): \r\n     vegetableComment = \"Is it a spicy \\(x)?\"\r\ndefault:\r\n     vegetableComment = \"Everything tastes good in soup.\"\r\n}\r\n\r\nprintln(vegetableComment)\r\n```\r\n\r\n\r\n## do,while使用\r\n\r\n```swift\r\nvar n = 2\r\n\r\n//条件在开始\r\nwhile n < 100 { \r\n    n = n * 2\r\n}\r\n\r\n//条件在结尾\r\ndo {\r\n    m = m * 2\r\n} while m < 100\r\n \r\n\r\n\r\n//范围\r\nvar firstForLoop = 0\r\nfor i in 0..<4 { //等同于：for var i = 0; i < 4; ++i \r\n    firstForLoop += i\r\n}\r\n\r\n```\r\n\r\n#0..<4 不包括4，如果要包括4，使用 0...4#\r\n\r\n\r\n\r\n## 函数和闭包\r\n\r\n```swift\r\n\r\n//函数申明\r\n\r\nfunc greet函数名(name: String, day: String)函数参数 ->返回值 String {\r\n    return \"Hello \\(name), today is \\(day).\"\r\n}\r\ngreet(\"Bob\", \"Tuesday\")\r\n\r\nfunc sumOf(numbers: Int...)参数个数不固定 -> Int {\r\n    var sum = 0\r\n    for number in numbers {\r\n        sum += number\r\n    }\r\n    return sum\r\n}\r\nsumOf()\r\nsumOf(42, 597, 12)\r\n\r\n\r\n//返回一个元组\r\nfunc calculateStatistics(scores: [Int]) -> (min2: Int, max2: Int, sum2: Int) {\r\n    var min = scores[0]\r\n    var max = scores[0]\r\n    var sum = 0\r\n\r\n    for score in scores {\r\n        if score > max {\r\n            max = score\r\n        } else if score < min {\r\n            min = score\r\n        }\r\n        sum += score\r\n    }\r\n\r\n    return (min, max, sum)\r\n}\r\nlet statistics = calculateStatistics([5, 3, 100, 3, 9])\r\n\r\nprintln(statistics)\r\nprintln(statistics.sum2) //使用返回元组的名称来取值\r\nprintln(statistics.1) //索引来取值\r\n\r\n//输出结果：\r\n//(3, 100, 120)\r\n//120\r\n//100\r\n\r\n\r\n\r\n//函数做为返回值，以及函数嵌套\r\nfunc makeIncrementer() -> (String -> Int) {   //(String -> Int) 与返回函数的参数数据类型和返回值相同\r\n    func addOne(number: String) -> Int {\r\n         var a:Int? = number.toInt()\r\n         if let b = a\r\n         {\r\n            return 1+b\r\n         }\r\n         else {return 1}\r\n    }\r\n    return addOne\r\n}\r\nvar increment = makeIncrementer() //调用了makeIncrementer函数，返回addOne函数\r\nprintln(increment(\"7\"))  //return 8\r\n\r\n\r\n//函数当做参数传入另一个函数\r\nfunc hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool { //condition: Int -> Bool 参数函数的值和返回值定义\r\n    for item in list {\r\n        if condition(item) {\r\n            return true\r\n        }\r\n    }\r\n    return false\r\n}\r\nfunc lessThanTen(number: Int) -> Bool {\r\n    return number < 10\r\n}\r\nvar numbers = [20, 19, 7, 12]\r\nhasAnyMatches(numbers, lessThanTen)\r\n```\r\n\r\n### 闭包\r\n```swift\r\nlet closure1  = {\r\n    (number: Int) -> Int in  //用in将参数和返回值类型声明与闭包函数体进行分离\r\n    let result = 3 * number\r\n    return result\r\n}\r\n//等同于：\r\nlet closure1  = {number in 3 * number} //参数类型默认为Int型，通过 3* 来自动识别，返回计算结果\r\n//等同于：\r\nlet closure1  = {3 * $0} //一切都是默认的，使用参数位置来访问参数\r\n\r\nprintln(closure1(1))\r\n```\r\n\r\n## 对象和类\r\n\r\n```swift\r\nclass NamedShape {\r\n    var numberOfSides: Int = 0\r\n    var name: String  //必须被初始化，或者定义为：var name: String?\r\n\r\n    init(name: String) {  //构造方法\r\n        self.name = name //初始化 name\r\n    }\r\n    deinit {\r\n        println(\"deinitialized\")\r\n    }\r\n    func simpleDescription() -> String {\r\n        return \"A shape with \\(numberOfSides) sides.\"\r\n    }\r\n}\r\n\r\n//继承\r\nclass EquilateralTriangle: NamedShape {\r\n    var sideLength: Double = 0.0\r\n\r\n    init(sideLength: Double, name: String) {\r\n        self.sideLength = sideLength\r\n        super.init(name: name) //父方法\r\n        numberOfSides = 3 //父变量\r\n    }\r\n\r\n    var perimeter: Double {  //geter 和 seter 方法，不能和 willSet（set前） 和 didSet（set后） 共存\r\n        set {\r\n            sideLength = newValue / 3.0\r\n        }\r\n        get {\r\n            return 3.0 * sideLength\r\n        }\r\n    }\r\n\r\n    override func simpleDescription() -> String {  //覆盖父方法\r\n        return \"An equilateral triagle with sides of length \\(sideLength).\"\r\n    }\r\n}\r\n\r\nclass Triangle {\r\n    var triangle: EquilateralTriangle { //申明 类 类型的变量\r\n        willSet {\r\n            println(newValue)\r\n        }\r\n    }\r\n    var square:Double = 1{  //同时初始化\r\n        willSet {\r\n            triangle.sideLength = newValue\r\n            println(\"willSet \\(newValue)\")\r\n        }\r\n        didSet(oldValue2) {\r\n            println(\"didSet \\(oldValue2)\")\r\n        }\r\n    }\r\n    init(size: Double, name: String) {\r\n        println(\"init\")\r\n        triangle = EquilateralTriangle(sideLength: size, name: name)  //初始化变量\r\n    }\r\n}\r\n\r\nvar t = Triangle(size: 12, name: \"assd\")\r\nt.square=21\r\n\r\n``` \r\n\r\n\r\n### didSet 实例\r\n```swift\r\nclass Foo\r\n{\r\n    var propertyChangedListener : (Int, Int) -> Void = {  //一个返回为空，有两个参数的类方法\r\n        println(\"The value of myProperty has changed from \\($0) to \\($1)\")\r\n    }\r\n\r\n    var myProperty : Int = 0 {\r\n        didSet { propertyChangedListener(oldValue, self.myProperty) }\r\n    }\r\n}\r\nvar f = Foo()\r\nf.myProperty = 1\r\n```\r\n\r\n\r\n## 枚举\r\n\r\n```swift\r\nenum CompassPoint:Int {\r\n  case North=1  //case 可以是一行或多行。给枚举项添加一个原始值如1，则其它的会自动叠加，如South值为2\r\n  case South,East\r\n  case West\r\n  \r\n  func simpleDescription() -> String { //扩展一个方法\r\n        switch self {\r\n        case .North:\r\n            return \"北\"\r\n        case .South:\r\n            return \"南\"\r\n        case .East:\r\n            return \"东\"\r\n        case .West:\r\n            return \"西\"\r\n        default:\r\n            return String(self.rawValue)\r\n        }\r\n    }\r\n}\r\n\r\nvar c = CompassPoint.North.rawValue //读取原始值\r\nvar c2 = CompassPoint.North //CompassPoint.init(rawValue:2) 通过原始值来取值\r\n\r\nprintln(c)\r\n\r\nc2 = .East //已知为CompassPoint类型，可以直接.East\r\n\r\nswitch c2 {\r\n    case .East :\r\n        println(c2.simpleDescription())\r\n    case .North :\r\n        println(\"c2\")\r\n    default:\r\n        println(\"aa\")\r\n}\r\n\r\n//相关值\r\n//原始值是预先设置好的，可以通过rawValue读取。而相关值是可以在具体使用过程中指定。\r\nenum Barcode {\r\n  case UPCA(Int, Int, Int) \r\n  case QRCode(String)\r\n}\r\n\r\nvar productBarcode = Barcode.UPCA(8, 85_909_51226, 3)\r\nproductBarcode = .QRCode(\"ABCDEFGHIJKLMNOP\")\r\n\r\n//读取相关值，注意let的用法。\r\nswitch productBarcode {\r\n    case .UPCA(let numberSystem, let identifier, let check):\r\n        println(\"UPC-A with value of \\(numberSystem), \\(identifier), \\(check).\")\r\n    case let .QRCode(productCode):\r\n        println(\"QR code with value of \\(productCode).\")\r\n}\r\n```\r\n\r\n\r\n## 协议（接口）和扩展\r\n\r\n### 协议\r\n\r\n```swift\r\nprotocol ExampleProtocol {\r\n    var simpleDescription: String { get }\r\n    mutating func adjust() //如果是枚举或结构实现此协议，在方法前加mutating，协议方法前面必须加mutating关键字。\r\n}\r\n\r\nclass SimpleClass: ExampleProtocol {\r\n    var simpleDescription: String = \"A very simple class.\"\r\n    var anotherProperty: Int = 69105\r\n    func adjust() {  //类方法前不需要加mutating\r\n        simpleDescription += \"  Now 100% adjusted.\"\r\n    }\r\n}\r\nvar a = SimpleClass()\r\na.adjust()\r\n```\r\n\r\n### 扩展\r\n```swift\r\nextension Int: ExampleProtocol {  //对原生的类方法扩展额外的功能\r\n    var simpleDescription: String { //给Int型数据添加方法simpleDescription\r\n        return \"The number \\(self)\"\r\n    }\r\n    mutating func adjust() { //使用mutating关键词声明了一个方法adjust改动了Int结构\r\n        self += 42\r\n    }\r\n}\r\n\r\n或者：\r\nextension Int { \r\n    var simpleDescription: String { \r\n        return \"The number \\(self)\"\r\n    }\r\n}\r\n\r\nprintln(7.simpleDescription)\r\n```\r\n\r\n\r\n## 泛型\r\n```swift\r\nfunc repeat<ItemType>(item: ItemType, times: Int) -> [ItemType] {  //ItemType 将被自动识别为String\r\n    var result = [ItemType]() \r\n    for i in 0..<times {\r\n        result.append(item)\r\n    }\r\n    return result\r\n}\r\nrepeat(\"knock\", 4)\r\n```\r\n\r\n## 类和结构\r\n\r\n类和结构基本相同，最大的区别是类是**引用类型**，结构是**值类型**！\r\n\r\n```swift\r\n//定义一个结构，里面的变量自动生成构造\r\nstruct task{\r\n    var name = \"name\"\r\n    var desc = \"desc\"\r\n}\r\nvar t1 = task(name:\"1\", desc:\"222\") //结构里面的变量自动生成构造\r\nvar t2 = t1\r\nt2.name = \"name xxx\" //不影响t1的值\r\nprintln(t1.name)\r\n\r\n\r\nclass a{\r\n    var a = 1\r\n    var b = 2\r\n}\r\nvar a1 = a()\r\nvar a2 = a1\r\na2.a=3 //会影响a1的值\r\nprintln(a1.a)\r\n```"},"comment":{"url":"https://api.github.com/repos/aliencode/aliencode.github.io/issues/comments/73636255","html_url":"https://github.com/aliencode/aliencode.github.io/issues/1#issuecomment-73636255","issue_url":"https://api.github.com/repos/aliencode/aliencode.github.io/issues/1","id":73636255,"user":{"login":"aliencode","id":2787688,"avatar_url":"https://avatars.githubusercontent.com/u/2787688?v=3","gravatar_id":"","url":"https://api.github.com/users/aliencode","html_url":"https://github.com/aliencode","followers_url":"https://api.github.com/users/aliencode/followers","following_url":"https://api.github.com/users/aliencode/following{/other_user}","gists_url":"https://api.github.com/users/aliencode/gists{/gist_id}","starred_url":"https://api.github.com/users/aliencode/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/aliencode/subscriptions","organizations_url":"https://api.github.com/users/aliencode/orgs","repos_url":"https://api.github.com/users/aliencode/repos","events_url":"https://api.github.com/users/aliencode/events{/privacy}","received_events_url":"https://api.github.com/users/aliencode/received_events","type":"User","site_admin":false},"created_at":"2015-02-10T03:00:04Z","updated_at":"2015-02-10T03:00:04Z","body":"函数调用参数名省略规则，，内部函数调用必须指定所有参数名，，全局函数调用省略第一个参数名，，参考：http://swifter.tips/func-naming/"}}