Apple在WWDC 2014开发者大会上发布了用于Mac OS X和iOS编程的新一代编程语言Swift。html
在真正可以使用Swift以前,SF先带你们从Apple的Beta版文档中,简单的一览Swift的基础用法。ios
SEGMENTFAULT声明:本文是根据**未发布版本**的文档编译整理而成的。
咱们没法保证苹果公司将来实际发布的软件,与本文的状况彻底一致。
编程
注:不要错过文章末尾的《SF简评Swift》部分!
swift
println("Hello world")
//
和/* */
。但块注释能够嵌套。/* A /* B */ C */
就是合法的。=
运算符仅用于赋值var = value
不是一个合法的表达式==
运算符仍然是判断var length = 10
let MAX_LENGTH = 100
var length: Double = 10
(var or let)println("Length = " + length + " cm")
println("Length = " + String(length) + " cm")
println("Length = \(length) cm")
nil
?
,显式指定变量能够赋空值:var optionalString: String? = nil
(定义或运行时都可)nil
在逻辑判断中被隐式转换为false (这与一般的变量值不得隐式转换不一样)另外,若是待引用的变量值多是nil
,通常须要先行判断。但在Swift中,能够在下标、方法或对象成员的引用以前加?
。
这个语法表示若是?
前边的是nil
,则后边的调用所有省略,整个表达式的值是nil
。segmentfault
WWDC 2014会上,Craig Federighi 直接展现了这个用法,将数行带有预判断的代码缩成了一行:数组
[value 1, value 2, value 3]
["key1": value 1, "key2": value 2]
[]
,空字典:[:]
注意:Swift中任何条件判断,必须使用真正的布尔值表达式!数值不会按照“0/非0”的习惯规则隐式转换为true,而是一概报错。网络
if condition 1 { code for condition 1 } else if condition 2 { code for condition 2 } else { code for none of above }
if
语句中,小括号可选,大括号必须。switch variable { case value 1: code for value 1 case value 2: code for value 1 default: code for none of abolve }
break
case value 1, value 2:
(值1或值2)case let x where x > 10:
default
分支不得省略。for var_iterator in iterated_array { code within loop }
for (key, value) in iterated_dictionary
..
指定整数的范围:for index in 1..5
for var index = 0; index < 3; ++index { code within loop }
while condition { code } do { code } while condition
func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday")
func f1(p1: Int...) -> Int {code}
调用f1(1, 2, 3)
return (3.59, 3.69, 3.79)
(借助tuple)函数容许嵌套。子函数共享父函数的变量做用域:闭包
func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen()
函数自己是一种数据类型。函数能够做为返回值:app
func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7)
也能够把函数自己,做为参数传递给其余函数:less
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, lessThanTen)
但必须注意类型必须严格等同。
可使用{}
定义匿名函数。能够在花括号内的第一行,使用in
关键字定义参数和返回值:
numbers.map({ (number: Int) -> Int in let result = 3 * number return result })
numbers.map({ number in 3 * number })
sort([1, 5, 3, 12, 2]) { $0 > $1 }
定义:
class Shape { var numberOfSides = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } }
实例化:
var shape = Shape("Triangle") shape.numberOfSides = 3 println(shape.simpleDescription())
init(name: String) {self.name = name}
deinit() {code}
:
super
关键字引用父类override
关键字class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()
可以自定义赋值或取值的代码的变量被称为属性(property)。
get
自定义取值,使用set
自定义赋值get
代码段中使用return
返回取值结果set
代码段中固定使用newValue
来表示传入的值willSet
和didSet
,在赋值先后执行代码(不影响赋值自己)class Circle { init(radius: Double) { self.radius = radius } var radius: Double { didSet { perimeter = radius * 6.28 } } var perimeter: Double { get { return 6.28 * radius } set { radius = newValue / 6.28 } } } circle = Circle(10) circle.perimeter // 62.8 circle.perimeter = 31.4 circle.radius // 5
使用enum
建立枚举量。枚举量有轻度的对象特性——能够在枚举量中使用方法。
enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } } let ace = Rank.Ace let aceRawValue = ace.toRaw() // 1
使用toRaw
和fromRaw
转换原始值和字面值:
if let convertedRank = Rank.fromRaw(11) { let jackDescription = convertedRank.simpleDescription() // "Jack" } let jackIndex = Rank.toRaw(Rank.Jack) // 11
上边的例子中,因为扑克牌存在数字意义的原始值,因此从Ace开始提供了一个1,然后按顺序自动增长。但Swift的枚举类型,为了没有数字意义的枚举量,也支持不使用原始值的定义方法:enum Color {case Red, Green, Blue}
也能够在枚举量上开辟变量空间,用来存储一些必要的值:
enum ServerResponse { case Result(String, String) case Error(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.") switch success { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failure... \(error)" }
结构体使用struct
定义,其定义语法和类很是类似。结构体支持构造器、成员方法等类的特性。
注意:结构体是按值传递的,而类/对象是按引用传递的。
struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription()
使用protocol
定义协议:
protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }
协议能够用在类、枚举和结构体上。
class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription
用extension
定义扩展,用来为已有的类型增长新的功能:
extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription
使用<>
声明泛型:
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] { var result = ItemType[]() for i in 0..times { result += item } return result } repeat("knock", 4)
泛型能够用在类、枚举和结构体上。
// Reimplement the Swift standard library's optional type enum OptionalValue<T> { case None case Some(T) } var possibleInteger: OptionalValue<Int> = .None possibleInteger = .Some(100)
使用where
对泛型提出一些约束:
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3])
Swift无疑是本次WWDC 2014中,贴近苹果开发者的最大亮点。
Swift并非对语言思想的本质革新,而是从当前的各类优秀语言中博采众家之长,从而制成为苹果平台提供的优秀工具。
Swift尤为是对于各类“坑”的处理很是用心。例如:
这些对于新手和老手而言,都是好的。“减轻新手痛苦,节约老手时间”——我想起了这一句广告词。
咱们相信Swift(至少在部分场合下)做为Objective-C的代用语言,将在苹果开发过程当中发挥不可或缺的做用。
咱们目前主要对Swift存疑的地方有:
咱们不肯意作任何的预先判断,只期待Swift公布后实际的表现如何。
苹果官方文档:(Pre-relase,发布前版本)
A Swift Tour, The Swift Programming Language, iOS Developer Library — Pre-Release
本文不少内容来自于对该文档的翻译。
来自其余做者的同一译文:来自苹果的编程语言——Swift简介
如何评价 Swift 语言?
新发布的 Swift 语言对初学者来讲是新的机遇吗?
SegmentFault编译原创文章,转载请遵照本站相关声明。 外文原做者:Apple Inc. 编译与原创部分:沙渺 责任编辑:沙渺