首页 > 代码库 > Swift基础知识整理

Swift基础知识整理

定义一个数组:

var a:[String]=["File", "Edit", "View", "Navigate"]

定义一个字典:

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

定义一个NSMutableDictionary数组

var a:[String]=["File", "Edit", "View", "Navigate"]var d: NSMutableDictionary = ["Xcode": "name", "6.1.1": "version", "qq":a]

将字典转化为json数据:

var jsonData = http://www.mamicode.com/NSJSONSerialization.dataWithJSONObject(dictionary, options:nil, error: nil)

将json转化为字典数据:

let jsonDatas = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .MutableContainers, error: nil) as NSDictionary

json与服务器进行数据交互

1、用NodeJs建立一个简单的web服务,吐出json数据:

var http=require(‘http‘)var port = ‘8081‘var data = http://www.mamicode.com/{‘name‘: ‘jifeng‘, ‘company‘: ‘taobao‘};http.createServer(function (req, res) {    res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=UTF-8‘,‘Server‘:‘NodeJs‘});    res.end(JSON.stringify(data));}).listen(port, "127.0.0.1");

2、用swift原生类请求数据:

var url = NSURL(string: "http://localhost:8081")var request = NSURLRequest(URL: url!)NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{    (response, data, error) -> Void in    if (error? != nil) {        //Handle Error here        print(error)    }else{        let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary        println(jsonData)        //Handle data in NSData type    }    })

 

Swift基础知识整理