swift Alamofire+ObjectMapper——swift(学习九)

Alamofire

Alamofire是目前为止我接触的swift最好的第三方下载库,它根本就不需要另外封装,所有的下载方法都是class func。同时呢,它提供了很多种回调的方法:

//最简单下载
Alamofire.request(.GET, "https://httpbin.org/get")
//带参数
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]).response { (request, response, data, error) in})
//URL转码
Alamofire.request(Method.GET, "https://httpbin.org/get", parameters: nil, encoding: ParameterEncoding.URL,headers: nil).responseString { (response) in

})

另外它的返回值有很多种,比如response、responseJSON、responseString等闭包。我自己最喜欢用的就是responseString。这里呢,也普及一下responseString返回对象都有哪些属性:

//response闭包,它包含返回的result与是否正确的bool状态
 print("response:- \(response)")
//请求相关的东西,打印出一个可选型的URL
 print("request:-\(response.request)")
//包含有可选型的URL、状态、请求头;请求头里有日期大小等
 print("response:-\(response.response)")
//打印出的二进制
 print("data:-\(response.data)")
//打印时间相关
 print("time:-\(response.timeline.totalDuration)")

所以我们最终需要的就只是result.value。

而有时候我们是需要返回进度的东西,有一点需要注意的是进度闭包不是在主线程的,所以要使用进度的时候要把它放到主线程里。

public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {}

下载还有一个经常用到的就是时间控制了,这个东西很坑的一点就是网上很多加时间限制的方法是错误的。因为时间限制是加在URLSession上的confige上的。

把以上几点综合一下,我封装了一个下载的函数:

/**下载
     *  host:是所有下载地址前面共有的域名地址,path:是请求地址,如果没有host,则只需要穿入path就可以
     *  timeout:请求限制时长
     *  params:请求要带的参数,这个可以用字典传进来,也可以手动添加在path上,用&连接
     *  completeHandle:回调闭包,返回的是一个JSONString
     *  progressHandle:进度闭包,返回一个实时进度,这个要在主线程使用进度
     */
    class func handleRequest(host:String?=nil,path:String?=nil,timeout:NSTimeInterval? = 5,params:[String: AnyObject]? = nil,completeHandle:(JSONString: String?)->Void,progressHandle:((progress:NSInteger)->Void)?=nil,cache:Bool) {

        if (host == nil)&&(path==nil) {
            return
        }

        var url:String?

        if host != nil {
            url = String.init(format:"%@?%@",host!,path!)
        }else{
            url = String.init(format:"%@",path!)
        }

        let manager = Alamofire.Manager.sharedInstance
        manager.session.configuration.timeoutIntervalForRequest = timeout!
        manager.session.configuration.timeoutIntervalForResource = timeout!

        manager.request(.GET, url!, parameters: params, encoding: ParameterEncoding.URL)
            .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
                dispatch_async(dispatch_get_main_queue()) {
                    print("Total bytes read on main queue: \(totalBytesRead)")
                    print("Progress on main queue: \(Float(totalBytesRead) / Float(totalBytesExpectedToRead))")
                }
            }.responseString { (response) in
                /*这里的response返回的不单单是
                 */
                print("response:- \(response)")
                print("request:-\(response.request)")
                print("response:-\(response.response)")
                print("data:-\(response.data)")
                print("time:-\(response.timeline.totalDuration)")
                switch response.result{
                    case .Success:
                        completeHandle(JSONString: response.result.value)
                    case .Failure(let error):
                        print(error)
                        let controller = UIAlertController.init(title: "request faile", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
                        controller.addAction(UIAlertAction.init(title: "sure", style: UIAlertActionStyle.Cancel, handler: { (action) in

                        }))
                        UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(controller, animated: true, completion:nil)
                }
            }
    }

ObjectMapper

聊完下载,聊解析,也是我认为最简单易用的解析库了,使用起来很简单:

//
//  TodayNewModel.swift
//  FCFTemplete
//
//  Created by 冯才凡 on 16/6/17.
//  Copyright ? 2016年 fcf. All rights reserved.
//

/*
 response:- SUCCESS: {
 "status": 1,
 "msg": "获取数据成功",
 "data": {
 "count": 4915,
 "results": [
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-16",
 "newsId": "e4933aae499aa472deca09b20d39addd",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/b383a34a9861a976aed20ed9311accc0.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16732",
 "newsNum": 0,
 "newsSource": "伯乐在线",
 "newsTitle": "史上比较用心的纯代码实现 AutoLayout",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "7f221c0246",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-16",
 "newsId": "0bca3c1214c24ff16e954f4eeb8ef2c5",
 "newsImage": "http://cc.cocimg.com/api/uploads/160615/de1c4afd4212a4676d277ca2a36026e8.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16718",
 "newsNum": 0,
 "newsSource": "天狐博客 投稿",
 "newsTitle": "盘点:Xcode 8新特性",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "61fe963f6c",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-16",
 "newsId": "1b0068df2cd12aca06a56b76442105da",
 "newsImage": "http://cc.cocimg.com/api/uploads/160615/eba436de53154c3401a9e95dd9558353.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16719",
 "newsNum": 0,
 "newsSource": "yohunl 投稿",
 "newsTitle": "iOS日志获取和实时浏览器显示日志",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "88c4cae808",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-16",
 "newsId": "60ac53300b27af1cca2637dc4bceef8c",
 "newsImage": "http://cc.cocimg.com/api/uploads/160612/03c5cdc13d6e6454a75b01088250c122.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16660",
 "newsNum": 0,
 "newsSource": "西木柚子的简书",
 "newsTitle": "UIWebView保存图片",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "da47d66725",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:02",
 "newsCreateTime": "2016-06-16",
 "newsId": "f820a89094f98a8cbc72f035dbad8eb4",
 "newsImage": "http://cc.cocimg.com/api/uploads/160615/1d0a09a33dfc82a447d65ea46ea83e7a.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16708",
 "newsNum": 0,
 "newsSource": "antscript 投稿",
 "newsTitle": "ASHUD——用Swift写的HUD库(OS X)",
 "newsType": "swift",
 "newsTypeName": "Swift",
 "objectId": "1cab10f595",
 "updatedAt": "2016-06-16 14:00:02"
 },
 {
 "createdAt": "2016-06-16 14:00:03",
 "newsCreateTime": "2016-06-16",
 "newsId": "68f829c79226b87a763d3e125a93df0c",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/d3ace468a57c259ff98d18c11f852b34.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16726",
 "newsNum": 0,
 "newsSource": "ASO100情报中心",
 "newsTitle": "开发者后台重大更新——展示量将成为衡量 ASO 重要标准",
 "newsType": "appstore",
 "newsTypeName": "App Store研究",
 "objectId": "867424f8df",
 "updatedAt": "2016-06-16 14:00:03"
 },
 {
 "createdAt": "2016-06-16 14:00:04",
 "newsCreateTime": "2016-06-16",
 "newsId": "371869ab00ecb682d432a34beef31cd7",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/0f8888e95688591c9362a484a1c5e824.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16725",
 "newsNum": 0,
 "newsSource": "信息与交互设计",
 "newsTitle": "如何做好陌生领域产品的交互设计",
 "newsType": "design",
 "newsTypeName": "产品设计",
 "objectId": "a8c4097b44",
 "updatedAt": "2016-06-16 14:00:04"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "b23517b5cb2b7c92f1788304e07464c5",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/151e68ed5a2a3735321231ae602f5aed.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16731",
 "newsNum": 0,
 "newsSource": "IT之家",
 "newsTitle": "iOS 10开发者预览版新特性:手游也要玩直播?",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "7ac8b9671e",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "78a1697515d0dffa7dd1fedd6df19e0e",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/c4e5386f1f76c0f59e806a57e5f48450.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16730",
 "newsNum": 0,
 "newsSource": "中关村在线",
 "newsTitle": "苹果官方回应系统应用“隐藏式”卸载",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "9fa041383f",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "96abf9746109d279d49ddddc16f561f0",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/7ab5ce4915b918d551be2642a31f36bc.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16729",
 "newsNum": 0,
 "newsSource": "IT之家",
 "newsTitle": "苹果iOS10弹窗提醒用户更新非64位应用:拖慢系统性能",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "88fdccb8aa",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "e94c2fa2f95a2497d4dca50930340843",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/a7a04578a6486e70f7847ea9083bd814.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16728",
 "newsNum": 0,
 "newsSource": "中关村在线",
 "newsTitle": "传iPhone 7取消双摄像头:因技术不成熟",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "3b1afb96a5",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "8a8e2a3c8d31d066270c788d0333d2c4",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/b947fed1b16f91e423132ce25bea6091.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16727",
 "newsNum": 0,
 "newsSource": "中关村在线",
 "newsTitle": "目标年底 苹果正为Apple Watch 2采购元件",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "fc810e0e5e",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "facdbebd932b2eb60a88c7f54bd6b150",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/9512490536c8bf15224627821d9014a3.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16723",
 "newsNum": 0,
 "newsSource": "SwiftCafe",
 "newsTitle": "没有硬件发布的 WWDC 2016—macOS篇",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "fa0004a1c3",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "49ba128182ed0821d19bf249ee87e3a0",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/985c61b2efcd754c9d950313078912e8.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16722",
 "newsNum": 0,
 "newsSource": "少数派",
 "newsTitle": "想尝鲜?谈谈 iOS 10 开发者预览版体验感受",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "688d154eb2",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:06",
 "newsCreateTime": "2016-06-16",
 "newsId": "aff01d5fb56c3a0f3b722599f9f144a1",
 "newsImage": "http://cc.cocimg.com/api/uploads/160616/9701035f5f1ff2e0e28c3585b0d58ad3.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16721",
 "newsNum": 0,
 "newsSource": "爱范儿",
 "newsTitle": "10 个重磅更新之外,iOS 10 还向这个设计趋势靠拢",
 "newsType": "apple",
 "newsTypeName": "苹果相关",
 "objectId": "bad7257619",
 "updatedAt": "2016-06-16 14:00:06"
 },
 {
 "createdAt": "2016-06-16 14:00:09",
 "newsCreateTime": "2016-06-16",
 "newsId": "6171059e63356d6c7fc4991f5a660ff2",
 "newsImage": "http://cc.cocimg.com/api/uploads/160615/85e61609b1e0a1a646d7da0b5abd6839.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16720",
 "newsNum": 0,
 "newsSource": "东京IT人",
 "newsTitle": "假如程序员生活在童话里……",
 "newsType": "programmer",
 "newsTypeName": "程序人生",
 "objectId": "f3ed350d5c",
 "updatedAt": "2016-06-16 14:00:09"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-15",
 "newsId": "4103e8b24c743c7d0ae55f290537eda6",
 "newsImage": "http://cc.cocimg.com/api/uploads/160614/0327d8b3d630232d7e05893764f4decd.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16704",
 "newsNum": 0,
 "newsSource": "MrPeak技术分享",
 "newsTitle": "一款快速生成代码的Xcode插件FastStub",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "4f95a60dd0",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-15",
 "newsId": "830e07d1817367e098241c1269811d0d",
 "newsImage": "http://cc.cocimg.com/api/uploads/160614/a01739b78ef2642bff8ee6ce0bdc33e1.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16652",
 "newsNum": 0,
 "newsSource": "Bison 投稿",
 "newsTitle": "分分钟解决iOS开发中App启动广告的功能",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "2064c463a3",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-15",
 "newsId": "b0d0ad4aafb33933fcf31b01464ab84a",
 "newsImage": "http://cc.cocimg.com/api/uploads/160614/cfddce2b3de30f0d2c55d29c0cd26c95.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16703",
 "newsNum": 0,
 "newsSource": "SwiftCafe",
 "newsTitle": "快速上手 Core Spotlight",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "5f956e57b8",
 "updatedAt": "2016-06-16 14:00:01"
 },
 {
 "createdAt": "2016-06-16 14:00:01",
 "newsCreateTime": "2016-06-15",
 "newsId": "ad99486dcf16ae6f6a6e17755f620304",
 "newsImage": "http://cc.cocimg.com/api/uploads/160614/1b1ca129ad219ea729eb75d1f9be6a8d.jpg",
 "newsLink": "http://www.cocoachina.com/cms/wap.php?action=article&id=16674",
 "newsNum": 0,
 "newsSource": "汉斯哈哈哈的简书",
 "newsTitle": "YYCache源码分析(二)",
 "newsType": "ios",
 "newsTypeName": "iOS开发",
 "objectId": "f2b2618d16",
 "updatedAt": "2016-06-16 14:00:01"
 }
 ]
 }
 }

 */

import UIKit
import ObjectMapper

class resultObj: Mappable {
    var createdAt:String?
    var newsCreateTime:String?
    var newsId:String?
    var newsImage:String?
    var newsLink:String?
    var newsNum:NSNumber?
    var newsSource:String?
    var newsTitle:String?
    var newsType:String?
    var newsTypeName:String?
    var objectId:String?
    var updatedAt:String?
    required init?(_ map: Map) {
    }
    func mapping(map: Map) {
        createdAt <- map["createdAt"]
        newsCreateTime <- map["newsCreateTime"]
        newsId <- map["newsId"]
        newsImage <- map["newsImage"]
        newsLink <- map["newsLink"]
        newsNum <- map["newsNum"]
        newsSource <- map["newsSource"]
        newsTitle <- map["newsTitle"]
        newsType <- map["newsType"]
        newsTypeName <- map["newsTypeName"]
        objectId <- map["objectId"]
        updatedAt <- map["updatedAt"]
    }
}

class dataObj: Mappable {
    var count:NSNumber?
    var results:[resultObj]?
    required init?(_ map: Map) {
    }
    func mapping(map: Map) {
        count <- map["count"]
        results <- map["results"]
    }
}

class TodayNewModel: Mappable {
    var status:Int?
    var msg:String?
    var data:dataObj?
    init(){}
    required init?(_ map: Map) {
    }

    func mapping(map: Map) {
        status <- map["status"]
        msg <- map["msg"]
        data <- map["data"]
    }
}
//这里需要提示一下的是:很多网上教程说要在func mapping(map: Map)函数里加一个mapping(map),不知道是不是我理解错的原因,但是就我这里的解析来说,在里面加mapping(map)是错误的做法,会无限递归下去的。

OK,model里大概就是这样了。那下载好了的时候,我们只需要把它们结合起来使用就可以了:

FCFBaseViewModel.handleRequest(nil, path: "http://cloud.bmob.cn/f8bb56aa119e68ee/news_list_2_0", timeout:10, params: (["limit":20,"skip":0]), completeHandle: { (returnValue) in
        print("************************************")
        print(returnValue)
        let result = Mapper<TodayNewModel>().map(returnValue)
        if let obj = result {
            let res = (obj.data?.results![0])! as resultObj
            print(res.newsTitle!)
        }
        }, progressHandle: nil, cache: false)
时间: 2024-11-07 23:36:25

swift Alamofire+ObjectMapper——swift(学习九)的相关文章

Welcome to Swift (苹果官方Swift文档初译与注解二十九)---209~218页(第四章-- 流程控制)

Break break语句会立刻结束整个流程控制的执行.break语句可以在switch语句或者循环语句中帮助你提前结束循环或者switch的执行. Break in a Loop Statement  (循环语句中的break) 当在循环语句中使用break,会立刻结束循环的执行,并且跳转到循环体之后的第一行代码.循环不会再遍历执行了. Break in a Switch Statement (switch语句的break) 当在switch语句中使用break,break会立刻结速switc

Swift编程语言翻译与学习——数组

Swift 语言提供经典的数组和字典两种集合类型来存储集合数据.数组用来按顺序存储相同类型的数据.字典虽然无序存储相同类型数据值但是需要由独有的标识符引用和寻址(就是键值对). Swift 语言里的数组和字典中存储的数据值类型必须明确. 这意味着我们不能把不正确的数据类型插入其中. 同时这也说明我们完全可以对获取出的值类型非常自信. Swift 对显式类型集合的使用确保了我们的代码对工作所需要的类型非常清楚,也让我们在开发中可以早早地找到任何的类型不匹配错误. 注意: Swift 的数组结构在被

Welcome to Swift (苹果官方Swift文档初译与注解十九)---123~132页(第二章..本章节还剩6页)

Working with Characters (与字符相关) 在Swift中,String类型表示一组有序字符的值.每个字符都是一个Unicode符号.可以使用for-in循环来遍历字符串中的每个字符: for character in "Dog!??" {   println(character) } // D // o // g // ! // ?? 在Swift中也可以使用Character类型来显式的创建一个单字符的常量或者变量: let yenSign: Character

Welcome to Swift (苹果官方Swift文档初译与注解三十五)---248~253页(第五章-- 函数 完)

Function Types as Return Types (函数类型作为返回值类型) 一个函数的类型可以作为另一个函数的返回值类型.可以在一个函数的返回值箭头后面写上一个完整的函数类型. 例如: 下面的例子定义了两个简单的函数,分别为stepForward 和 stepBackward.其中stepForward函数返回值比它的输入值多1,stepBackward函数返回值比它输入值少1.这两个函数的 类型都是(Int) -> Int: func stepForward(input: Int

Welcome to Swift (苹果官方Swift文档初译与注解二十七)---189~198页(第四章-- 流程控制)

Switch 一个switch语句里包含一个值,并且用这个值与其他几个可能的匹配模式进行比较,然后根据成功匹配上的模式,执行相应的代码块.switch语句提供了比if语句更多的选项来相应多种潜 在的情况. 最简单的一个例子: switch some value to consider { case value 1:   respond to value 1 case value 2, value 3:   respond to value 2 or 3 default:   otherwise,

Welcome to Swift (苹果官方Swift文档初译与注解二十一)---140~147页(第三章--集合类型)

第三章 Collection Types (集合类型) 在Swift中,提供了两种集合类型用来存储一组值:数组和字典.数组有序的存储相同类型的值;字典存储无序的相同类型的值.字典可以通过唯一的标识(就是所说的键)来查询和访问. 在Swift中,数组和字典总是要清晰的标明他们存储数据的类型.这就意味着不可以将错误的类型插入到数组或字典中.同时也意味着你是明确了解你要遍历的数组或字典里面数据的类 型.在Swift中,集合要显式的声明类型来保证在开发中都会明确的知道它能处理的数据类型. 注意点: 在S

Welcome to Swift (苹果官方Swift文档初译与注解十一)---70~76页(第二章)

Type Aliases (类型别名) 类型别名是个已经存在的类型定义另一个名字.定义类型别名的时候,使用关键字typealias. 当你想要使用名字来引用一个已经存在的类型时,类型别名将非常有效,并且更适合代码的上下文理解.例如,当要处理指定大小的一个数据时: typealias AudioSample = UInt16 一旦定义了一个类型别名,就可以在任何地方来代替原来的类型名: var maxAmplitudeFound = AudioSample.min // maxAmplitudeF

Welcome to Swift (苹果官方Swift文档初译与注解十)---63~69页(第二章)

如果你将整型与浮点型一起使用,结果将被认为是Double类型: et anotherPi = 3 + 0.14159 // anotherPi 的类型是Double 上述代码中,3的值是没有明确说明类型,因此,根据剩余部分的浮点类型可以确定返回值为Double. Numeric Literals (数值的进制表示) 整数类型可以进行如下表示: A decimal number, with no prefix         // 十进制数值,不需要前缀符号; A binary number, w

Welcome to Swift (苹果官方Swift文档初译与注解三)---11~18页

上述代码中,如果可选值为nil,那么判断条件则为false,而且在{}中的代码将会被忽略,如果可选值不为nil,会将该值逐步运算后赋值给let后面的常量,其中逐步运算过程将依据实际的代码块. Switch 语法支持任何类型数据以及各种比较操作,并不局限在整型. let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some rai