从今天开始学习Swift -- Swift 初见 (转)
原文地址:http://www.cocoachina.com/newbie/basic/2014/0604/8675.html
println("hello, world")
| 注意:为了获得最好的体验,在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。 |
var myVariable =
myVariable =
let myConstant =
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 = 0
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()
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
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()
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([, , ], [])
从今天开始学习Swift -- Swift 初见 (转)的更多相关文章
- Swift语法初见
Swift语法初见 http://c.biancheng.net/cpp/html/2424.html 类型的声明: let implicitInteger = 70 let implicitDoub ...
- ios swift学习日记1-Swift 初见
最近ios的swift语言似乎火了,我没有objectc基金会,但在此之前有cjava的基础的.从这几天開始学习ios的swift语言.后期以博客形式公布.这里提供一本翻译的英文版的swif书籍. 还 ...
- 【Swift学习】Swift编程之旅(三)
元组(tuples) tuples是将多个单一的值组合为一个复合的值.它可以包含任何类型的值,而不需要都是相同类型. 一.元组的创建 1. let http404error = (,"NOT ...
- 【Swift学习】Swift编程之旅(一)
学习一门新语言最经典的例子就是输出“Hello World!” print("Hello World!") swift就是这样来输出的. 如果你使用过其他语言,那么看上去是非常的熟 ...
- Swift 学习Using Swift mix and match, network: 写rss读者
有使用第三方库.因此,需要使用mix and match财产. 请指出错误,谢谢! rss 阅读器,非常easy的代码.仅仅是为了学习swift语言而写. 1、BaseViewController.s ...
- swift swift学习笔记--函数和闭包
使用 func来声明一个函数.通过在名字之后在圆括号内添加一系列参数来调用这个方法.使用 ->来分隔形式参数名字类型和函数返回的类型 func greet(person: String, day ...
- Swift 学习 用 swift 调用 oc
开发过程中 很可能 把swift不成熟的地方用成熟的oc 代码来弥补一下 , 下面简单来学习一下,我也是照着视频 学习的 卖弄谈不上 就是一次学习笔记, 具体问题还是具体分析吧. 需求 给展出出来的 ...
- 【Swift学习】Swift编程之旅---可选链(二十一)
可选链Optional Chaining是一种可以在当前值可能为nil的可选值上请求和调用属性.方法及下标的方法.如果可选值有值,那么调用就会成功:如果可选值是nil,那么调用将返回nil.多个调用可 ...
- 【Swift学习】Swift编程之旅---ARC(二十)
Swift使用自动引用计数(ARC)来跟踪并管理应用使用的内存.大部分情况下,这意味着在Swift语言中,内存管理"仍然工作",不需要自己去考虑内存管理的事情.当实例不再被使用时, ...
随机推荐
- slice()、substring()、substr()的区别用法
在js中字符截取函数有常用的三个slice().substring().substr()了,下面我来给大家介绍slice().substring().substr()函数在字符截取时的一些用法与区别吧 ...
- 【图灵学院15】极致优化-高性能网络编程之BIO与NIO区别
一.Java IO概念 1. 一个http请求节点 数据传输 1)网络传输 TCP.UDP 2)通信模型 BIO.NIO.AIO 数据处理 3)应用协议 HTTP.RMI.WEBSERVICE.Re ...
- django 学习之DRF (一)
Django框架基础DRF-01 前后端分离介绍 1.前后端不分离图解 2.前后端分离图解 3.为什么要学习DRF DRF可以帮助我们开发者快速的开发⼀个依托于Django的前后后端分离 ...
- shell脚本学习一
shell脚本是一种程序与linux内核的语言: 第一个shell脚本: #!/bin/bash echo "cxy" 就是输出cxy 如何执行这个脚本呢: cd demo 进入s ...
- Qt 学习之路 2(16):深入 Qt5 信号槽新语法
Qt 学习之路 2(16):深入 Qt5 信号槽新语法 豆子 2012年9月19日 Qt 学习之路 2 53条评论 在前面的章节(信号槽和自定义信号槽)中,我们详细介绍了有关 Qt 5 的信号 ...
- cs231n学习笔记(二)图像分类
图像分类可说是计算机视觉中的基础任务同时也是核心任务,做好分类可为检测,分割等高阶任务打好基础. 本节课主要讲了两个内容,K近邻和线性分类器,都是以猫的分类为例. 一. K近邻 以猫的分类为例,一张含 ...
- 树莓派编译安装 EMQ 服务器
前言 EMQ 是一款开源的物联网 MQTT 消息服务器,使用 Erlang/OTP 语言平台设计,在 DIY 智能家居时可以作为网关,前几天摸索了一下在树莓派中安装 EMQ 的方法,记录一下. 步骤 ...
- python BeautifulSoup基本用法
#coding:utf-8 import os from bs4 import BeautifulSoup #jsp 路径 folderPath = "E:/whm/google/src_j ...
- Python的安装位置与Python库
如何查看Python的安装位置: 输入 where python ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ...
- 读经典——《CLR via C#》(Jeffrey Richter著) 笔记_NGen.exe
NGen.exe:本地代码生成器. [作用] 加快应用程序的启动速度 减小应用程序的工作集 [缺点] 没知识产权保护 生成的文件不能及时同步 执行时性能较差 [建议] 客户端考虑使用