Swift语法出来时间不长,网络上的各种教程已经铺天盖地,但是基本上所有的教程都是来自官方翻译。从Swift出来到现在,每天都在学习Swift,下面给出个人感受
虽然Swift语言很简单,手机相对于Objective-c要快,但是一些原理的东西还是起源于Objective-c,框架中虽然包括了Swift API,但是API的设计很多都是苹果特有的,掌握一直到熟练,个人感觉与学习Objective-c不会相差太多。Swift是一个拉开档次的语言,我想他的出现会终结靠Objective-c语法吃饭那些人的高薪,对于那些懂得思想的人,Swift会成为一把利剑,让高手开发起来更加得心应手
Swift的一些语法还是比较有意思的,这里给出几个小的代码片段,测试一下你看懂了没有:
1、隐式类型与拆封(?与!)
let possibleString: String? = "An optional string." if possibleString { println(possibleString) } let number1 = possibleString!.toInt() //compile error let number2 = possibleString.toInt()
var str: String = "str" var nsStr: NSString = "NSString" var selector: Selector = "selector" var selector2: Selector = Selector("") str = nsStr nsStr = str
var tuple: (str: Int, str2: Int) = (2, 3) tuple.str = 4 tuple.1 = 2 let tuple2 = (4, 5) //compile error let2.0 = 1
var closurea: (Int, Int) -> Bool = { n1, n2 in return n1 > n2} var closureb: (Int, Int) -> Bool = {$0 > $1}
func add(#number: Int) -> () -> Int { var ret = 0 func incrementor() -> Int { ret += number return ret } return incrementor } let incrementor = add(number: 10) incrementor() incrementor() println(incrementor())
var closure1: @auto_closure () -> Int? = {return 3}() var closure2: @auto_closure () -> Int = 3 closure1() closure2()
struct TestStruct1 { var test: String = "struct" } let struct1 = TestStruct1(test: "1111") struct TestStruct2 { var test: String = "struct" init() { } } //compile error let struct2 = TestStruct2(test: "2222")
原文:http://blog.csdn.net/g1jun/article/details/30245311