国外开发者最近发现,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