The Swift Programming Language-官方教程精译Swift(1)小试牛刀
println("hello, world")
注意:为了获得最好的体验,在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。 |
let implicitInteger =
let implicitDouble = 70.0
let explicitDouble: Double =
let label = "The width is"
let width =
let widthLabel = label + String(width)
let apples =
let oranges =
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[] = "bottle of water" var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
shoppingList = [] // 去逛街并买点东西
let individualScores = [, , , , ]
var teamScore =
for score in individualScores {
if score > {
teamScore +=
} else {
teamScore +=
}
}
teamScore
var optionalString: String? = "Hello"
optionalString == nil var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
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": [, , , , , ],
"Fibonacci": [, , , , , ],
"Square": [, , , , ],
]
var largest =
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest
var n =
while n < {
n = n *
}
n var m =
do {
m = m *
} while m <
m
var firstForLoop =
for i in .. {
firstForLoop += i
}
firstForLoop var secondForLoop =
for var i = ; i < ; ++i {
secondForLoop +=
}
secondForLoop
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
func getGasPrices() -> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
getGasPrices()
func sumOf(numbers: Int...) -> Int {
var sum =
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(, , )
func returnFifteen() -> Int {
var y =
func add() {
y +=
}
add()
return y
}
returnFifteen()
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return + number
}
return addOne
}
var increment = makeIncrementer()
increment()
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 <
}
var numbers = [, , , ]
hasAnyMatches(numbers, lessThanTen)
numbers.map({
(number: Int) -> Int in
let result = * number
return result
})
sort([, , , , ]) { $ > $ }
class Shape {
var numberOfSides =
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
var shape = Shape()
shape.numberOfSides =
var shapeDescription = shape.simpleDescription()
这个版本的Shape类缺少了一些重要的东西:一个构造函数来初始化类实例。使用init来创建一个构造器。
class NamedShape {
var numberOfSides: Int =
var name: String init(name: String) {
self.name = name
} func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: NamedShape {
var sideLength: Double init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides =
} 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()
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0 init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides =
} 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
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: , name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square(sideLength: , name: "larger square")
triangleAndSquare.triangle.sideLength
class Counter {
var count: Int =
func incrementBy(amount: Int, numberOfTimes times: Int) {
count += amount * times
}
}
var counter = Counter()
counter.incrementBy(, numberOfTimes: )
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
enum Rank: Int {
case Ace =
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()
if let convertedRank = Rank.fromRaw() {
let threeDescription = convertedRank.simpleDescription()
}
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()
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()
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)"
}
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int =
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 +=
}
} .simpleDescription
练习:给Double类型写一个扩展,添加absoluteValue功能。
let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription
// protocolValue.anotherProperty // Uncomment to see the error
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
var result = ItemType[]()
for i in ..times {
result += item
}
return result
}
repeat("knock", )
// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some()
在类型名后面使用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([, , ], [])
The Swift Programming Language-官方教程精译Swift(1)小试牛刀的更多相关文章
- The Swift Programming Language-官方教程精译Swift(9) 枚举-- --Enumerations
枚举定义了一个通用类型的一组相关的值,使你可以在你的代码中以一个安全的方式来使用这些值. 如果你熟悉 C 语言,你就会知道,在 C 语言中枚举指定相关名称为一组整型值.Swift 中的枚举更加灵活 ...
- The Swift Programming Language-官方教程精译Swift(8)闭包 -- Closures
闭包是功能性自包含模块,可以在代码中被传递和使用. Swift 中的闭包与 C 和 Objective-C中的 blocks 以及其他一些编程语言中的 lambdas 比较相似. 闭包可以捕获和存储其 ...
- The Swift Programming Language-官方教程精译Swift(7)函数 -- Functions
函数 函数是执行特定任务的代码自包含块.通过给定一个函数名称标识它是什么,并在需要的时候使用该名称来调用函数以执行任务. Swift的统一的功能语法足够灵活的,可表达任何东西,无论是不带参数名称的简单 ...
- The Swift Programming Language-官方教程精译Swift(6)控制流--Control Flow
Swift提供了类似C语言的流程控制结构,包括可以多次执行任务的for和while循环,基于特定条件选择执行不同代码分支的if和switch语句,还有控制流程跳转到其他代码的break和continu ...
- The Swift Programming Language-官方教程精译Swift(5)集合类型 -- Collection Types
Swift语言提供经典的数组和字典两种集合类型来存储集合数据.数组用来按顺序存储相同类型的数据.字典虽然无序存储相同类型数据值但是需要由独有的标识符引用和寻址(就是键值对). Swift语言里的数 ...
- The Swift Programming Language-官方教程精译Swift(4)字符串和字符
String 是一个有序的字符集合,例如 "hello, world", "albatross".Swift 字符串通过 String 类型来表示,也可以表示为 ...
- The Swift Programming Language-官方教程精译Swift(3)基本运算符
运算符是检查, 改变, 合并值的特殊符号或短语. 例如, 加号 + 把计算两个数的和(如 let i = 1 + 2). 复杂些的运行算包括逻辑与&&(如 if enteredDoor ...
- The Swift Programming Language-官方教程精译Swift(2)基础知识
Swift 的类型是在 C 和 Objective-C 的基础上提出的,Int是整型:Double和Float是浮点型:Bool是布尔型:String是字符串.Swift 还有两个有用的集合类型,Ar ...
- 一群牛人翻译:The Swift Programming Language 中文版
无聊闲逛GIthub,看到一群牛人在github上创建了一个关于Switf的文档翻译项目 The Swift Programming Language 中文版 项目地址:中文版 Apple 官方 Sw ...
随机推荐
- web前端知识体系小结(转)
1. 前言 大约在几个月之前,让我看完了<webkit技术内幕>这本书的时候,突然有了一个想法.想把整个web前端开发所需要的知识都之中在一个视图中,形成一个完整的web前端知识体系,目的 ...
- AM335x(TQ335x)学习笔记——u-boot-2014.10移植
根据最近移植u-boot-2014.10至TQ335x,基于这样的假设am335x evm移植.不是很多地方需要改变. 因为TI的am335x evm开发了使用eeprom船上保存配置信息.它使用不同 ...
- nginx: [emerg] the size 10485760 of shared memory zone "cache_one" conflicts with already declared size 0
注意配置段中的区域包含关系. proxy_cache_patch 要在proxy_cache前已经定义. what seems to be the problem? [emerg]: the size ...
- web自定义炫酷字体
电脑有已经安装好的字体,但是如果你有特殊需要而要选择其他字体,则需要以下几个步骤 1.寻找适合你的字体 有下面几个站点提供字体下载: www.theleagueofmoveabletype.com w ...
- PHP操作数据库PDO
PHP操作数据库 载入数据库驱动 訪问phpinfo.php能够查看是否已经载入数据库驱动,例如以下显示还没有载入mySql数据库驱动. 在c盘找到php.ini配置文件开启载入mySql驱动,例如以 ...
- Linux
介绍了相关的文件夹
学习Linux,先了解Linux标准的文件夹结构是非常重要的,学习的一个很好的铺垫之后的行动.去罗列大而全的所有文件夹. 本文主要说明.笔者本人接触,须要了解的一些文件文件夹,当然本文也会不断的更新或 ...
- 【Linux&Unix--文件描述叙事的性格和权柄】
个人学习整理,如有不足之处,请不吝不吝赐教.转载请注明:@CSU-Max 系列博文: Linux&Unix学习第一弹 -- 文件描写叙述符与权限 L ...
- .NET反编译之Reflector基础示例
这几日由于公司需要, 看了些.NET反编译技巧,特地和大家分享下 .NET反编译工具很多,Reflector是其中一个很优秀的工具,所以就用它来进行反编译工作了.今天我们就用"繁星代码生成器 ...
- Cocos2d-X中的坐标系
在Cocos2d-x中坐标能够分成四种: 1.GL坐标体系:GL坐标体系左下角为坐标原点,X轴向右,Y轴向上 2.UI坐标体系:UI坐标体系左上角为坐标原点,X轴向右,Y轴向上. .世界坐标体系:是窗 ...
- Log4j 2.0在具体解释发展先进的使用—SocketAppender远程输出(五岁以下儿童)
Log4j2的Appenders充分考虑输出日志事件.包装和过滤可以被转发,它包含的主要输出到本地文件.输出到远程主机, 文件包.注射.而且,根据该日志文件的时间点.自己主动文件大小的储存条件. 例如 ...