Swift概览
<pre name="code" class="objc">转自:http://letsswift.com/2014/06/swift_overview/
Swift Programming Language中的A Swift Tour。
world
println("Hello, world")
变量与常量
var myVariable = 42
myVariable = 50
let myConstant = 42
类型推导
let explicitDouble : Double = 70
let label = "The width is "
let width = 94
let width = label + String(width)
字符串格式化
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let appleSummary = "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"
一般使用初始化器(initializer)语法创建空数组和空字典:
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
var optionalString: String? = "Hello"
optionalString == nil var optionalName: String? = "John Appleseed"
var gretting = "Hello!"
if let name = optionalName {
gretting = "Hello, \(name)"
}
灵活的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."
}
其他循环
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
var n = 2
while n < 100 {
n = n * 2
}
n var m = 2
do {
m = m * 2
} while m < 100
m
Swift支持传统的for循环,此外也能够通过结合..(生成一个区间)和for-in实现相同的逻辑。
var firstForLoop = 0
for i in 0..3 {
firstForLoop += i
}
firstForLoop var secondForLoop = 0
for var i = 0; i < 3; ++i {
secondForLoop += 1
}
secondForLoop
注意:Swift除了..还有…:..生成前闭后开的区间,而…生成前闭后闭的区间。
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
通过元组(Tuple)返回多个值:
func getGasPrices() -> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
getGasPrices()
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
函数也能够嵌套函数:
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
作为头等对象,函数既能够作为返回值,也能够作为參数传递:
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
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)
闭包
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
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
创建Shape类的实例,并调用其字段和方法。
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
使用deinit进行清理工作。
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()
注意:假设这里的simpleDescription方法没有被标识为override,则会引发编译错误。
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triagle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
注意:赋值器(setter)中,接收的值被自己主动命名为newValue。
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
triangleAndSquare.triangle.sideLength
从而保证triangle和square拥有相等的sideLength。
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes times: Int) {
count += amount * times
}
}
var counter = Counter()
counter.incrementBy(2, numberOfTimes: 7)
注意Swift支持为方法參数取别名:在上面的代码里,numberOfTimes面向外部,times面向内部。
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional
square")
let sideLength = optionalSquare?.sideLength
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()
使用toRaw和fromRaw在原始(raw)数值和枚举值之间进行转换:
if let convertedRank = Rank.fromRaw(3) {
let threeDescription = convertedRank.simpleDescription()
}
注意:枚举中的成员值(member value)是实际的值(actual value),和原始值(raw value)没有必定关联。
enum Suit {
case Spades, Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()
除了能够关联方法,枚举还支持在其成员上关联值,同一枚举的不同成员能够有不同的关联的值:
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 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 ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
类型、枚举和结构都能够实现(adopt)协议:
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 Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
7.simpleDescription
泛型(generics)
func repeat(item: ItemType, times: Int) -> ItemType[] {
var result = ItemType[]()
for i in 0..times {
result += item
}
return result
}
repeat("knock", 4)
Swift也支持在类、枚举和结构中使用泛型:
// Reimplement the Swift standard library's optional type
enum OptionalValue {
case None
case Some(T)
}
var possibleInteger: OptionalValue = .None
possibleInteger = .Some(100)
有时须要对泛型做一些需求(requirements),比方需求某个泛型类型实现某个接口或继承自某个特定类型、两个泛型类型属于同一个类型等等,Swift通过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])
本文转自Lucida的博客 感谢原作者
Swift概览的更多相关文章
- 2.Swift教程翻译系列——Swift概览
英文版PDF下载地址http://download.csdn.net/detail/tsingheng/7480427 依照传统学习程序语言都是从hello,world開始,在Swfit里面仅仅须要一 ...
- The Swift Programming Language 中文翻译版(个人翻新随时跟新)
The Swift Programming Language --lkvt 本人在2014年6月3日(北京时间)凌晨起来通过网络观看2014年WWDC 苹果公司的发布会有iOS8以及OS X 10.1 ...
- [iOS翻译]《The Swift Programming Language》系列:Welcome to Swift-01
注:CocoaChina翻译小组已着手此书及相关资料的翻译,楼主也加入了,多人协作后的完整译本将很快让大家看到. 翻译群:291864979,想加入的同学请进此群哦.(本系列不再更新,但协作翻译的进度 ...
- Swift 新语言开发
全书文件夹: 一.Welcome to Swift 二.Language Guide 三.Language Reference /* 译者的废话: 几个小时前熬夜看了WWDC,各种激动,今年非常有料啊 ...
- Swift の 函数式编程
Swift 相比原先的 Objective-C 最重要的优点之一,就是对函数式编程提供了更好的支持. Swift 提供了更多的语法糖和一些新特性来增强函数式编程的能力,本文就在这方面进行一些讨论. S ...
- The Swift Programming Language 中文翻译版
原文(http://www.cnblogs.com/lkvt/p/3765349.html) 一.Welcome to Swift 1.关于Swift Swift是一种用于iOS和OS X应用的全新编 ...
- SWIFT语言的概览
Swift用来写iOS和OS X程序.(估计也不会支持其它屌丝系统) Swift吸取了C和Objective-C的优点,且更加强大易用. Swift可以使用现有的Cocoa和Cocoa Touch框架 ...
- Developing iOS8 Apps with Swift——iOS8概览
iOS 8 概览 斯坦福公开课--Developing iOS8 Apps with Swift学习笔记 想学习Swift,但是相应的教程不是很多,在CoCoaChina社区闲逛时恰好发现了这门课程, ...
- Swift 语言概览 -自己在Xcode6 动手写1
原文:Swift 语言概览 -自己在Xcode6 动手写1 Swift是什么? Swift是苹果于WWDC 2014发布的编程语言,这里引用The Swift Programming Language ...
随机推荐
- usaco /the second wave
bzoj4582:简单递推题. #include<cstdio> #include<cstring> #include<iostream> #include< ...
- Mysql slave 状态之Seconds_Behind_Master
在MySQL的主从环境中,我们可以通过在slave上执行show slave status来查看slave的一些状态信息,其中有一个比较重要的参数Seconds_Behind_Master.那么你是否 ...
- 【Web前沿技术】纯 CSS3 打造的10个精美加载进度条动画
之前向大家介绍8款优秀的 jQuery 加载动画和进度条插件,今天这篇文章向大家推荐10个纯 CSS3 代码实现精美加载进度条动画效果的方案.加载动画和进度条在网站和 Web 应用中的使用非常流行,特 ...
- Gradle使用手册(一):为什么要用Gradle?
原文地址:http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Using-sourceCompatibility-1. ...
- golang资料整理 (整理 中...)
网站guide 官方文档 国内镜像 安装go 之后,用godoc 来安装自己本地的文档服务器, godoc -http=:8080 打开浏览器 输入localhost:8080 就可以看到文档说明了. ...
- Project Euler 26 Reciprocal cycles
题意:求1到n中所有数的倒数中循环小数循环体最长的数 解法:如果一个数的质因子只有2和5,那么这个数的倒数一定不是一个循环小数.如果一个数含有质因子2或5,那么它的循环体和去掉质因子2和5之后的数的循 ...
- 关于触发器、存储过程和DBlink的综合运用 (转)
关于触发器.存储过程和DBlink的综合运用 需求描述: 需要在两个不同oracl数据库实例中进行数据逻辑处理.如果A实例中的表有新数据插入或者数据更新,那么在B实例中执行与之相关的存储过程. 先假设 ...
- 1、WWDC2014 详解OSX/iOS8/Swift语言
OS X 10新特性 1.系统图标扁平化. 2.系统菜单栏可定制. 3.新的通知中心. 4.新的Spotlight. 5.新的iCloud Drive,新增文档同步功能(学Windows). 6.新的 ...
- HDU 5699 货物运输 二分判定
转自:http://blog.csdn.net/jtjy568805874/article/details/51480479 #include <cstdio> #include < ...
- HDU 5606 tree 并查集
tree 把每条边权是1的边断开,发现每个点离他最近的点个数就是他所在的连通块大小. 开一个并查集,每次读到边权是0的边就合并.最后Ansi=size[findset(i)],size表示每个并 ...