swift开发的技巧

在swift学习与开发中的一些tips.

1.NSTimer的选择器方法需要加@objc private

self.timer = NSTimer(fireDate: NSDate(timeIntervalSinceNow: 1), interval: 1.0, target: self, selector: "timerHandler", userInfo: nil, repeats: true)
@objc private func timerHandler() {///func detail}

2.readonly写法

private(set) public var isConnected: Bool?

3.从NSData里面取整数

let msgData:NSData()//获取到的比特流
var i = [UInt8](count:2, repeatedValue: 0) //2代表你要获取几位数
msgData.getBytes(&i, length: 2)
Int(i[0]),Int(i[1]) 从NSData里面取出来的整数

4.字符串截取子串

let targetStr = "ABCDEFGHI" 
let begin = targetStr.startIndex.advancedBy(3) //从前数三位
let end = targetStr.endIndex.advancedBy(-3) ///从后数三位
return targetStr.substringWithRange(Range(start: begin, end: end)) //得到的子串为"DEF"