Swift 横空出世
Apple Releases iOS 8 SDK With Over 4,000 New APIs
苹果2014-6-2日的WWDC开发者大会,是名符其实的“开发者大会”,发布新的操作系统,IOS8,4000+的新api,这已经让我们这些程序员够吐槽的了。不过苹果的技术大拿们似乎不满足于此,推出了新的开发语言--Swift。我要吐血啦,那些苹果顾的水军编辑们,竟然起哄,“coder们要喜大普奔”啊,艹,明显站着说话不腰疼啊!
吐槽归吐槽,Swift就这样横空出世了,以后会不会成为武林高手呢,咱拭目以待。不过对于咱这样的开发者,还是赶紧啃吧。
快速浏览了Swift语言之后,发现原来swift语言没有那么难,甚至能让一大部分开发者轻易的转战ios开发,这个语言的风格很大程度类似脚本js和python之类。嘿嘿,多少人在偷着乐啊。
Swift语言到底是何方神圣呢?咱看看苹果官方怎么说:
Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works.
看样子,苹果是要大力推动Swfit语言了,Swift可以用来在MAC和IOS上开发,兼容目前的Cocoa和Cocoa touch Framework,Swift吸收了安全编程模式的特点,同时摆脱了C语言的一些束缚,变的更加好用,易扩展,更有趣。(玩玩才知道)
Swift是如何摆脱C语言的一些束缚呢?还记得那个"hello world!"吗?
-
println("Hello, world")
这可不是一句表达式,这是一个完整的程序,是不是少点了很多的include,函数框架也没有了,特码的连main都不用,就是一句脚本,执行就ok了。凋爆了。
Swift的变量和语句很简单,两个关键词,var和let就可以搞定了:
-
var myVariable = 42
-
myVariable = 50
-
let myConstant = 42
强制要求初始化,初始值决定类型,想要制定类型怎么办,很简单:
-
let implicitInteger = 70
-
let implicitDouble = 70.0
-
let explicitDouble: Double = 70
类型转换不支持隐式,必须强转:
-
let label = "The width is "
-
let width = 94
-
let widthLabel = label + String(width)
猜猜这个“ \()
”是干嘛用的,哈哈!强转为字符串的利器:
-
let apples = 3
-
let oranges = 5
-
let appleSummary = "I have \(apples) apples."
-
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
数组,字典之类的比较中规中矩,没有什么好讲的,直接看效果:
-
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
-
shoppingList[1] = "bottle of water"
-
-
var occupations = [
-
"Malcolm": "Captain",
-
"Kaylee": "Mechanic",
-
]
-
occupations["Jayne"] = "Public Relations"
数组,字典的初始化,更加自由了,感觉像Java啦:
-
let emptyArray = String[]()
-
let emptyDictionary = Dictionary<String, Float>()
数组和字典在作为参数时,可以简写为[]和[:] .
程序流程控制方面,新特性比较多,常规的if,switch, for-in, for, while, do-while的用法都支持,不过在使用条件语句的时候,有了新的变化,比如if语句的==判断,语法是这样的:
-
var optionalString: String? = "Hello"
-
optionalString == nil
-
-
var optionalName: String? = "John Appleseed"
-
var greeting = "Hello!"
-
if let name = optionalName {
-
greeting = "Hello, \(name)"
-
}
注意到了上面的String类型之后的?了吗,这个是一个标注,表示这个值是可选的,就是可以给空值nil,还有一点,布尔值不在等同于0和其他int值了,必须用显性的bool值。
switch语句有个很大特色,条件支持任意类型了,看看下面的语句,我就觉得爽:
-
let vegetable = "red pepper"
-
switch vegetable {
-
case "celery":
-
let vegetableComment = "Add some raisins and make ants on a log."
-
case "cucumber", "watercress":
-
let vegetableComment = "That would make a good tea sandwich."
-
case let x where x.hasSuffix("pepper"):
-
let vegetableComment = "Is it a spicy \(x)?"
-
default:
-
let vegetableComment = "Everything tastes good in soup."
-
}
靠,没有break语句怎么跳出来啊?没有关系,Swift摒弃这个语法陋习。是不是减少了很多发错的机会。哈哈
待续:
已有 0 人发表留言,猛击->> 这里<<-参与讨论
ITeye推荐