Swift编程语言简介
这篇文章简要介绍了苹果于WWDC 2014发布的编程语言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 imagine how software development works.
Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.
|
println("Hello, world")
var myVariable =
myVariable =
let myConstant =
let explicitDouble : Double =
let label = "The width is "
let width =
let width = label + String(width)
let apples =
let oranges =
let appleSummary = "I have \(apples) apples."
let appleSummary = "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>()
let individualScores = [, , , , ]
var teamScore =
for score in individualScores {
if score > {
teamScore +=
} else {
teamScore +=
}
}
var optionalString: String? = "Hello"
optionalString == nil var optionalName: String? = "John Appleseed"
var gretting = "Hello!"
if let name = optionalName {
gretting = "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
})
numbers.map({ number in * number })
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.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()
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()
}
- c
lass 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
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编程语言简介的更多相关文章
- Apple Swift编程语言入门教程
Apple Swift编程语言入门教程 作者: 日期: 布衣君子 2015.09.22 目录 1 简介 2 Swift入门 3 简单值 4 控制流 5 函数与闭包 6 对象与类 ...
- [转]Swift 编程语言入门教程
今天在网上看到一篇非常好的教程,分享给大家 原文地址:http://gashero.iteye.com/blog/2075324 目录 1 简介 2 Swift入门 3 简单值 4 控 ...
- Swift 编程语言入门教程
1 简介 今天凌晨Apple刚刚发布了Swift编程语言,本文从其发布的书籍<The Swift Programming Language>中摘录和提取而成.希望对各位的iOS& ...
- TKT中文编程语言简介
TKT中文编程语言简介 TKT语言是新型的类似自然语言的汉语编程语言. 它是基于新的语言设计思想创造的语言,和现存的易语言.习语言.O语言.汉编等中文编程语言没有关系. TKT语言特点一: 中文编程 ...
- Swift编程语言(中文版)官方手册翻译(进度8.8%)
翻译着玩,进度会比较慢. 等不及的可以看CocoaChina翻译小组,他们正在组织翻译,而且人手众多,相信会提前很多完成翻译. 原文可以在iTunes免费下载 目前进度 7 JUN 2014: 8.8 ...
- iOS Swift编程语言
Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序. Swift是一款易学易用的编程 ...
- Swift编程语言资料合集
在本周二凌晨召开的苹果年度开发者大会WWDC上,苹果公司推出了全新的编程语言Swift.Swift 基于C和Objective-C,是供iOS和OS X应用编程的全新语言,更加高效.现代.安全,可以提 ...
- iOS中生成并导入基于Swift编程语言的Framework
从iOS 8.0开始就引入了framework打包方式以及Swift编程语言.我们可以主要利用Swift编程语言将自己的代码打包成framework.不过当前Xcode 7.x在自动导入framewo ...
- Swift编程语言中的方法引用
由于Apple官方的<The Swift Programming Guide>对Swift编程语言中的方法引用介绍得不多,所以这里将更深入.详细地介绍Swift中的方法引用. Swift与 ...
随机推荐
- Web前端开发规范手册
一.规范目的 1.1 概述 为提高团队协作效率, 便于后台人员添加功能及前端后期优化维护, 输出高质量的文档, 特制订此文档. 本规范文档一经确认, 前端开发人员必须按本文档规范进行前台页面开发. ...
- asp.net MVC之 自定义过滤器(Filter) - shuaixf
一.系统过滤器使用说明 1.OutputCache过滤器 OutputCache过滤器用于缓存你查询结果,这样可以提高用户体验,也可以减少查询次数.它有以下属性: Duration :缓存的时间, 以 ...
- erlang服务器启动,有情况会报,enif_send: env==NULL no ono-SMP VMAborted 的错误报告?
问题的原因所在: 1:因为你当前使用的主机是一个单核的主机(不会自动启动): 2:多核上如果不设置-smp enable是不会有什么问题的,因为从OTP R12B开始,如果操作系统报告有多于1个的CP ...
- JAVA内存管理
java与c++之间有一堵由内存动态分配和垃圾收集技术所围成的高墙.墙外面的人想进去,墙里面的人想出去. 1.java内存分布 程序计数器 栈(局部变量.操作数.动态链接.方法出口) 每一个方法从调用 ...
- C++小项目:directx11图形程序(八):particleSysclass
粒子系统类,粒子系统是游戏里细小元素的控制系统,虽然感觉上它对游戏的影响不大,但是其实有了它能给游戏增色不少.粒子系统控制着细小元素的生死,运动,纹理.对它的编写让我知道,游戏里的这一片从天空飘落的雪 ...
- Hibernate2
计应134(实验班) 杨伟 Hibernate 中提供了两级Cache(高速缓冲存储器),第一级别的缓存是Session级别的缓存,它是属于事务范围的缓存.这一级别的缓存由hibernate管理的,一 ...
- 让powershell同时只能运行一个脚本(进程互斥例子)
powershell,mutex,互斥,进程互斥,脚本互斥 powershell脚本互斥例子,在powershell类别文章中,声明原创唯一. powershell 传教士 原创文章 2016-07- ...
- 自定义cell(xib)中button点击事件不能响应的情况
遇到这种问题真的好尴尬,之前从来没有遇到过,以为手到擒来,未曾料到还会遇到问题! 好多年没有找到尴尬的感觉,现在找到了,真的很尴尬 ! *o* 1.首先使用场景: 原本没打算用xib,后来为了快速, ...
- 【转】Tomcat的默认访问路径
放在外网的应用,用户多是直接输入域名访问,相信没有哪个后面还加个尾巴,而Tomcat的默认目录是ROOT,所以我们需要更改其默认目录. 更改Tomcat的默认目录很简单,只需要修改server.xml ...
- NGUI如何使2D图片按像素1:1显示在屏幕上
NGUI版本为3.5.1. 将camera 设置为正交模式,size值设为1. UIRoot(2D)有3种缩放样式: 1.PixelPerfect.UI严格按照指定的像素大小显示,不会随着屏幕的分辨率 ...