u012460084的专栏

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

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

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

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

语言基础你好,,世界。// Swiftprintln("Hello, world!")// Scala */println("Hello, world!")变量与常量// Swiftvar myVariable = 42myVariable = myVariable = 42myVariable = 50val myConstant = 42显式类型val explicitDouble: Double = 70强制类型转换width = 94let widthLabel = label + String(width)//Scalaval label = "The width is "val width = 94val widthLabel = label + width字符串数据填充oranges = 5let fruitSummary = "I have \(apples + oranges) " + val apples = 3val oranges = 5val fruitSummary = s"I have ${apples + oranges} " +" pieces of fruit."整数半开区间运算符// Swiftlet names = ["Anna", "Alex", "Brian", "Jack"]let count = names.countfor i in 0..count {println("Person \(i + 1) is called \(names[i])")}val names = Array("Anna", "Alex", "Brian", "Jack")val count = names.lengthfor (i <- 0 until count) {println(s"Person ${i + 1} is called ${names(i)}")}整数闭区间运算符..5 {println("\(index) times 5 is \(index * 5)")}(index <- 1 to 5) {println(s"$index times 5 is ${index * 5}")}集合数组// Swiftvar shoppingList = ["catfish", "water","tulips", "blue paint"]shoppingList[shoppingList = Array("catfish","water", "tulips", "blue paint")shoppingList(1) = "bottle of water"字典// Swiftvar occupations = ["Malcolm": "Captain","Kaylee": "Mechanic",]occupations[occupations = scala.collection.mutable.Map("Malcolm" -> "Captain","Kaylee" -> "Mechanic")occupations("Jayne") = "Public Relations"空集// Swiftlet emptyArray = String[]()let emptyDictionary = Dictionary<String, Float>()let emptyArrayNoType = []// Scalaval emptyArray = Array[String]()val emptyDictionary = Map[String, Float]()val emptyArrayNoType = Array()函数函数定义// Swiftfunc greet(name: String, day: String) -> String {}greet("Bob", "Tuesday")// Scaladef greet(name: String, day: String): String = {return s"Hello $name, today is $day."}greet("Bob", "Tuesday")元组(Tuple)返回值// Swiftfunc getGasPrices() -> (Double, Double, Double) {return (3.59, 3.69, 3.79)}// Scaladef getGasPrices(): (Double, Double, Double) = {return (3.59, 3.69, 3.79)}可变数量参数// Swiftfunc sumOf(numbers: Int…) -> Int {number in numbers {sum += number}return sum}sumOf(42, 597, 12)// Scaladef sumOf(numbers: Int*): Int = {(number <- numbers) {sum += number}return sum}sumOf(42, 597, 12)函数作为数据类型// Swiftfunc makeIncrementer() -> (Int -> Int) {func addOne(number: Int) -> Int {+ number}return addOne}var increment = makeIncrementer()increment(7)// Scaladef makeIncrementer(): Int => Int = {def addOne(number: Int): Int = {+ number}return addOne}var increment = makeIncrementer()increment(7)集合迭代器(Map)// Swiftvar numbers = [20, 19, 7, 12]numbers.map({ number in 3 * number })// Scalavar numbers = Array(20, 19, 7, 12)numbers.map( number => 3 * number )排序// Swiftsort([1, 5, 3, 12, 2]) { $0 > $1 }// ScalaArray(1, 5, 3, 12, 2).sortWith(_ > _)命名参数// Swiftdef area(width: Int, height: Int) -> Int {return width * height}area(width: 10, height: 10)// Scaladef area(width: Int, height: Int): Int = {return width * height}area(width = 10, height = 10)类定义{func simpleDescription() -> String {}}{def simpleDescription(): String = {s"A shape with $numberOfSides sides."}}使用// Swiftvar shape = Shape()shape.numberOfSides = 7var shapeDescription = shape.simpleDescription()// Scalavar shape = new Shape()shape.numberOfSides = 7var shapeDescription = shape.simpleDescription()子类// Swiftclass NamedShape {var numberOfSides: Int = 0var name: Stringinit(name: String) {self.name = name}func simpleDescription() -> String {return "A shape with \(numberOfSides) sides."}}class Square: NamedShape {var sideLength: Doubleinit(sideLength: Double, name: String) {self.sideLength = sideLengthsuper.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()// Scalaclass NamedShape(var name: String) {var numberOfSides: Int = 0def simpleDescription() =s"A shape with $numberOfSides sides."}class Square(var sideLength: Double, name: String)extends NamedShape(name) {numberOfSides = 4def area() = sideLength * sideLengthoverride def simpleDescription() =s"A square with sides of length $sideLength."}val test = new Square(5.2, "my test square")test.area()test.simpleDescription()检查实例所属的类songCount = 0for item in library {if item is Movie {++movieCount} else if item is Song {++songCount}}songCount = 0for (item <- library) {if (item.isInstanceOf[Movie]) {} else if (item.isInstanceOf[Song]) {}}基类转派生类(向下转换)someObjects {Movieprintln("Movie: ‘\(movie.name)’, dir. \(movie.director)")}// Scalafor (obj <- someObjects) {val movie = obj.asInstanceOf[Movie]println(s"Movie: ‘${movie.name}’, dir. ${movie.director}")}协议// Swiftprotocol Nameable {func name() -> String}func f<T: Nameable>(x: T) {println("Name is " + x.name())}// Scalatrait Nameable {def name(): String}def f[T ) = {" + x.name())}扩展// Swiftextension 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.mmprintln("One inch is \(oneInch) meters")// prints "One inch is 0.0254 meters"let threeFeet = 3.ftprintln("Three feet is \(threeFeet) meters")Extensions {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.DoubleUnitval oneInch = 25.4.mmprintln(s"One inch is $oneInch meters")// prints "One inch is 0.0254 meters"val threeFeet = 3.ftprintln(s"Three feet is $threeFeet meters")// prints "Three feet is 0.914399970739201 meters"

人,总是很难改正自己的缺点,

u012460084的专栏

相关文章:

你感兴趣的文章:

标签云: