Swift 学习(一)

国外开发者最近发现,WWDC2014上苹果发布的新语言Swift,和古老的  Scala 语言在语法上存在众多的相似之处。



本文以苹果官方教程  The Swift Programming Language 中的示例,比较Swift与Scala两种语言实现同一功能的代码。

Swift语言从语法上来看,几乎是Scala的一个分支,在以下功能上几乎是等同的:类型继承、闭包、元组(Tuple)、协议、扩展、泛型等。

不过Swift的运行环境和Scala的区别还是很大,这个概念才是Swift最重要的。Scala语言编译成JVM程序,使用垃圾收集机制,与Java无缝整合。但Swift最终编译到机器代码,使用引用计数机制,与Objective-C无缝整合。所以Swift和Scala在代码表象上的相似,应该并不太影响两种语言本质机理上的重大不一致。

语言基础

你好,世界。

// Swift
println("Hello, world!")
// Scala */
println("Hello, world!")

变量与常量

// Swift
var myVariable = 42
myVariable = 50
let myConstant = 42

// Scala
var myVariable = 42
myVariable = 50
val myConstant = 42

显式类型

// Swift
let explicitDouble: Double = 70
// Scala
val explicitDouble: Double = 70

强制类型转换

// Swift
let label = "The width is "
let width = 94
let widthLabel = label + String(width)

//Scala
val label = "The width is "
val width = 94
val widthLabel = label + width

字符串数据填充

// Swift
let apples = 3
let oranges = 5
let fruitSummary = "I have \(apples + oranges) " +
  "pieces of fruit."

// Scala
val apples = 3
val oranges = 5
val fruitSummary = s"I have ${apples + oranges} " +
  " pieces of fruit."

整数半开区间运算符

// Swift
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..count {
  println("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

// Scala
val names = Array("Anna", "Alex", "Brian", "Jack")
val count = names.length
for (i <- 0 until count) {
  println(s"Person ${i + 1} is called ${names(i)}")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack

整数闭区间运算符

// Swift
for index in 1...5 {
  println("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

// Scala
for (index <- 1 to 5) {
  println(s"$index times 5 is ${index * 5}")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

集合

数组

// Swift
var shoppingList = ["catfish", "water",
  "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

// Scala
var shoppingList = Array("catfish",
  "water", "tulips", "blue paint")
shoppingList(1) = "bottle of water"

字典

// Swift
var occupations = [
  "Malcolm": "Captain",
  "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

// Scala
var occupations = scala.collection.mutable.Map(
  "Malcolm" -> "Captain",
  "Kaylee" -> "Mechanic"
)
occupations("Jayne") = "Public Relations"

空集

// Swift
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
let emptyArrayNoType = []

// Scala
val emptyArray = Array[String]()
val emptyDictionary = Map[String, Float]()
val emptyArrayNoType = Array()

函数

函数定义

// Swift
func greet(name: String, day: String) -> String {
  return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")

// Scala
def greet(name: String, day: String): String = {
  return s"Hello $name, today is $day."
}
greet("Bob", "Tuesday")

元组(Tuple)返回值

// Swift
func getGasPrices() -> (Double, Double, Double) {
  return (3.59, 3.69, 3.79)
}

// Scala
def getGasPrices(): (Double, Double, Double) = {
  return (3.59, 3.69, 3.79)
}

可变数量参数

// Swift
func sumOf(numbers: Int...) -> Int {
  var sum = 0
  for number in numbers {
    sum += number
  }
  return sum
}
sumOf(42, 597, 12)

// Scala
def sumOf(numbers: Int*): Int = {
  var sum = 0
  for (number <- numbers) {
    sum += number
  }
  return sum
}
sumOf(42, 597, 12)

函数作为数据类型

// Swift
func makeIncrementer() -> (Int -> Int) {
  func addOne(number: Int) -> Int {
    return 1 + number
  }
  return addOne
}
var increment = makeIncrementer()
increment(7)

// Scala
def makeIncrementer(): Int => Int = {
  def addOne(number: Int): Int = {
    return 1 + number
  }
  return addOne
}
var increment = makeIncrementer()
increment(7)

集合迭代器(Map)

// Swift
var numbers = [20, 19, 7, 12]
numbers.map({ number in 3 * number })

// Scala
var numbers = Array(20, 19, 7, 12)
numbers.map( number => 3 * number )

排序

// Swift
sort([1, 5, 3, 12, 2]) { $0 > $1 }

// Scala
Array(1, 5, 3, 12, 2).sortWith(_ > _)

命名参数

// Swift
def area(width: Int, height: Int) -> Int {
  return width * height
}

area(width: 10, height: 10)

// Scala
def area(width: Int, height: Int): Int = {
  return width * height
}

area(width = 10, height = 10)

定义

// Swift
class Shape {
  var numberOfSides = 0
  func simpleDescription() -> String {
    return "A shape with \(numberOfSides) sides."
  }
}

// Scala
class Shape {
  var numberOfSides = 0
  def simpleDescription(): String = {
    return s"A shape with $numberOfSides sides."
  }
}

使用

// Swift
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

// Scala
var shape = new Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

子类

// Swift
class NamedShape {
  var numberOfSides: Int = 0
  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 = 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)
test.area()
test.simpleDescription()

// Scala
class NamedShape(var name: String) {
  var numberOfSides: Int = 0

  def simpleDescription() =
    s"A shape with $numberOfSides sides."
}

class Square(var sideLength: Double, name: String)
  extends NamedShape(name) {
  numberOfSides = 4
  def area() = sideLength * sideLength

  override def simpleDescription() =
    s"A square with sides of length $sideLength."
}

val test = new Square(5.2, "my test square")
test.area()
test.simpleDescription()

检查实例所属的类

// Swift
var movieCount = 0
var songCount = 0

for item in library {
  if item is Movie {
    ++movieCount
  } else if item is Song {
    ++songCount
  }
}

// Scala
var movieCount = 0
var songCount = 0

for (item <- library) {
  if (item.isInstanceOf[Movie]) {
    movieCount += 1
  } else if (item.isInstanceOf[Song]) {
    songCount += 1
  }
}

基类转派生类(向下转换)

// Swift
for object in someObjects {
  let movie = object as Movie
  println("Movie: ‘\(movie.name)‘, dir. \(movie.director)")
}

// Scala
for (obj <- someObjects) {
  val movie = obj.asInstanceOf[Movie]
  println(s"Movie: ‘${movie.name}‘, dir. ${movie.director}")
}

协议

// Swift
protocol Nameable {
  func name() -> String
}

func f<T: Nameable>(x: T) {
  println("Name is " + x.name())
}

// Scala
trait Nameable {
  def name(): String
}

def f[T <: Nameable](x: T) = {
  println("Name is " + x.name())
}

扩展

// Swift
extension Double {
  var km: Double { return self * 1_000.0 }
  var m: Double { return self }
  var cm: Double { return self / 100.0 }
  var mm: Double { return self / 1_000.0 }
  var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"

// Scala
object Extensions {
  implicit class DoubleUnit(d: Double) {
    def km: Double = { return d * 1000.0 }
    def m: Double = { return d }
    def cm: Double = { return d / 100.0 }
    def mm: Double = { return d / 1000.0 }
    def ft: Double = { return d / 3.28084 }
  }
}

import Extensions.DoubleUnit

val oneInch = 25.4.mm
println(s"One inch is $oneInch meters")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.ft
println(s"Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"
时间: 2024-11-13 10:46:55

Swift 学习(一)的相关文章

Swift 学习-多线程

1:第一种多线程 func fun1(){ for i in 200...300{ NSLog("%d",i); } } func fun2(){ for i in 300...400{ NSLog("%d",i); } } var th1 = NSThread(target:self,selector:"fun1",object:nil); th1.start(); //开启线程 NSThread.detachNewThreadSelector

SWIFT学习笔记05

1.Swift 无需写break,所以不会发生这种贯穿(fallthrough)的情况.2.//用不到变量名,可用"_"替换 for _ in 1...power { answer *= base } 3.case 可以匹配更多的类型模式,包括区间匹配(range matching),元组(tuple)和特定类型的描述. 可以这样用case case 1...3: naturalCount = "a few" 4.如果存在多个匹配,那么只会执行第一个被匹配到的 ca

SWIFT学习笔记02

1.//下面的这些浮点字面量都等于十进制的12.1875: let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0//==12+3*(1/16) 2.//类型别名,用typealias关键字来定义类型别名 typealias AudioSample = UInt16 var maxAmplitudeFound = AudioSample.min 3.//元组 let ht

swift学习笔记(三)关于拷贝和引用

在swift提供的基本数据类型中,包括Int ,Float,Double,String,Enumeration,Structure,Dictionary都属于值拷贝类型. 闭包和函数同属引用类型 捕获则为拷贝.捕获即定义这些常量和变量的原作用域已不存在,闭包仍然可以在闭包函数体内引用和修改这些值 class属于引用类型. Array的情况稍微复杂一些,下面主要对集合类型进行分析: 一.关于Dictionary:无论何时将一个字典实例赋给一个常量,或者传递给一个函数方法时,在赋值或调用发生时,都会

Swift学习笔记十二:下标脚本(subscript)

下标脚本就是对一个东西通过索引,快速取值的一种语法,例如数组的a[0].这就是一个下标脚本.通过索引0来快速取值.在Swift中,我们可以对类(Class).结构体(structure)和枚举(enumeration)中自己定义下标脚本的语法 一.常规定义 class Student{ var scores:Int[] = Array(count:5,repeatedValue:0) subscript(index:Int) -> Int{ get{ return scores[index];

Swift学习笔记四:数组和字典

最近一个月都在专心做unity3d的斗地主游戏,从早到晚,最后总算是搞出来了,其中的心酸只有自己知道.最近才有功夫闲下来,还是学习学习之前的老本行--asp.net,现在用.net做项目流行MVC,而不是之前的三层,既然技术在更新,只能不断学习,以适应新的技术潮流! 创建MVC工程 1.打开Visual studio2012,新建MVC4工程 2.选择工程属性,创建MVC工程 3.生成工程的目录 App_Start:启动文件的配置信息,包括很重要的RouteConfig路由注册信息 Conten

Swift学习——使用if和switch来进行条件操作,使用for,while,和do-while来进行循环(三)

Swift学习--使用if和switch来进行条件操作,使用for,while,和do-while来进行循环 //switch支持随意类型的数据以及各种比較操作--不不过整数以及測试相等 //注意假设去掉default程序会报错 let strings = "hello3" switch strings{ case "hello1": let stringsComment = "say hello1" println("stringsC

汇集了很多swift 学习指南

https://github.com/ipader/SwiftGuide 1,059   Unstar7,294 Fork1,966 ipader/SwiftGuide CodeIssues 0Pull requests 0WikiPulseGraphs 这份指南汇集了Swift语言主流学习资源,并以开发者的视角整理编排.http://dev.swiftguide.cn 376 commits 3 branches 0 releases 12 contributors Swift 100.0%

Apple Swift学习资料汇总

[更新]Apple Swift学习资料汇总 1月16日厦门 OSC 源创会火热报名中,奖品多多哦 »   今年的苹果开发者大会(WWDC)上,公布了ios8的几个新特性,其中包括引入了群聊功能,支持第三方输入法等功能.但更让开发者感兴趣的莫过于Swift语言的发布了. Swift是apple自创的一门转为cocoa和cocoa touch设计的语言,意用来替换objc.Swift能使代码大量简化,并且开发者们可以在同一款软件中同事使用obj-c,Swift,c语言.方便 开发者来学习这么语言.这

Swift学习——A Swift Tour 枚举和结构体

Enumerations and Structures Enumerations   枚举的使用 使用 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 { ca