Swift编程权威指南第2版 读后收获
classDog: NSObject{ letorigin: String= "中国" fileprivatevarname: String? privatevarage: Int? init(_name: String?, age: Int= 1) { self.name= name ?? "旺财" self.age= age } }
定义了一个Dog类,一个常量“origin”,当一个变量被定义成let型,则只能被赋值一次。“name”和”age”是两个可空类型的变量。重载了一个init方法,在init方法中有两个形参。“name”为可空类型,”age”的默认值为一。在init方法中将这两个变量赋值给属性。其中判断name有值就设置name,为空时设置默认值“旺财”。
let sum: ((Int,Int) -> Int) = {(a, b) in returna + b } let res = sum(1, 2) print(res) int(^SumBlock) (int, int) = ^(intx, inty) { return x + y; };
let str = "hello world" var str0 = str.prefix(2)//前两个 var str1 = str.suffix(2)//后两个 let index0 = str.index(str.endIndex, offsetBy: -4) var str2 = str[index0..<str.endIndex]//后4个 let index1 = str.index(str.startIndex, offsetBy: 4) var str3 = str[str.startIndex..<index1]//前4个
与OC的对比
NSString*str = @"hello world"; id str0 = [str substringToIndex:2]; id str1 = [str substringFromIndex:str.length-2]; id str2 = [str substringWithRange:NSMakeRange(2, 3)];
struct Animal { let region = "中国" var name: String? var color = UIColor.red init(name: String,color: UIColor) { self.name= name self.color= color } struct Dog { let legNum = 4 func run() -> String{ return"跑回家" } } }
enum SDCEnumType: Int{ case circle = 20 case check func enumTypeString(type: SDCEnumType) -> String{ switch type { case .circle: return"circle" default: if type.rawValue== 21{ return"check" } else{ return"其他情况" } } } enum SDCEnumSubType { case square(SDCEnumType) case ellipse(SDCEnumType) } }
protocol Student { var name: String{getset} var age: Int{get} static func study(date:Date) -> Date init(name:String) } extension Student{ var score:Float{ return80.8 } } protocol Childe:Student{ }
func SwapTwoValues <T> (inout a: T,inout b :T){ let tempValue = a a = b b = tempValue } structIntStack{ var items = [Int]() //压栈 mutating func push(item:Int){ items.append(item) } //出栈 mutating func pop()->Int{ return items.removeLast() } } struct Stack<Ele>{ var items = [Ele]() mutating func push(item:Ele){ items.append(item) } mutating func pop()->Ele{ return items.removeLast() } }
//前置运算符,表示2的var0次方 prefix operator ^ prefix func^ ( var0: Double) -> Double{ return pow(2, var0) } //后置运算符,表示var0的2次方 postfix operator ^ postfix func ^ (var0: Double) -> Double{ return var0*var0 }