Swift和Scala语法上的诸多相似之处

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

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

image.png

本文以苹果官方教程 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

letlabel = "The width is "

letwidth = 94

let widthLabel = label + String(width)

//Scala

val label = "The width is "

val width = 94

val widthLabel = label + width


字符串数据填充

// Swift

letapples = 3

letoranges = 5

letfruitSummary = "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 in0..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 in1...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 numberin numbers {

       sum += number

   }

   returnsum

}

sumOf(42, 597, 12)

// Scala

def sumOf(numbers: Int*): Int = {

   var sum = 0

   for (number <- numbers) {

       sum += number

   }

   returnsum

}

sumOf(42, 597, 12)

函数作为数据类型

// Swift

func makeIncrementer() -> (Int -> Int) {

   func addOne(number: Int) -> Int {

       return1 + number

   }

   return addOne

}

var increment = makeIncrementer()

increment(7)

// Scala

def makeIncrementer(): Int => Int = {

   def addOne(number: Int): Int = {

       return1 + number

   }

   return addOne

}

var increment = makeIncrementer()

increment(7)

集合迭代器(Map)

// Swift

var numbers = [20, 19, 7, 12]

numbers.map({ numberin3 * 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 {

   returnwidth * height

}

area(width: 10, height: 10)

// Scala

def area(width: Int, height: Int): Int = {

   returnwidth * height

}

area(width = 10, height = 10)

定义

// Swift

classShape {

   varnumberOfSides=0

   funcsimpleDescription() ->String {

       return"A shape with \(numberOfSides) sides."

   }

}

// Scala

classShape {

   varnumberOfSides=0

   defsimpleDescription(): String= {

       returns"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

classNamedShape {

   var numberOfSides: Int=0

   var name: String

   init(name: String) {

       self.name = name

   }

   funcsimpleDescription() -> String {

       return"A shape with \(numberOfSides) sides."

   }

}

classSquare: NamedShape {

   var sideLength: Double

   init(sideLength: Double, name: String) {

       self.sideLength = sideLength

       super.init(name: name)

       numberOfSides =4

   }

   funcarea() -> Double {

       return sideLength * sideLength

   }

   overridefuncsimpleDescription() -> String {

       return"A square with sides of length

               \(sideLength)."

   }

}

let test =Square(sideLength: 5.2)

test.area()

test.simpleDescription()

// Scala

classNamedShape(varname: String) {

   var numberOfSides: Int=0

   def simpleDescription() =

       s"A shape with $numberOfSides sides."

}

classSquare(varsideLength: Double, name: String)

   extendsNamedShape(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 inlibrary {

   if item is Movie {

       ++movieCount

   } elseif item is Song {

       ++songCount

   }

}

// Scala

var movieCount = 0

var songCount = 0

for (item <- library) {

   if (item.isInstanceOf[Movie]) {

       movieCount += 1

   } elseif (item.isInstanceOf[Song]) {

       songCount += 1

   }

}

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

// Swift

forobjectin someObjects {

   let movie = objectas 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

protocolNameable {

   funcname() -> String

}

funcf<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 classDoubleUnit(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"

相关文章
|
17天前
|
Java Swift C语言
Swift 基本语法
10月更文挑战第23天
14 1
|
3月前
|
存储 编译器 Swift
Swift笔记:Swift中的扩展语法
Swift笔记:Swift中的扩展语法
99 1
|
6月前
|
安全 Swift iOS开发
【Swift开发专栏】Swift基础语法详解
【4月更文挑战第30天】Swift是苹果2014年发布的编程语言,适用于iOS、macOS等多个平台。它比Objective-C更安全、现代、易学。本文主要介绍Swift基础:常量变量(`let`和`var`),数据类型(整数、浮点数、布尔、字符串),元组,可选类型(Optional)。此外,还涉及运算符(算术、比较、逻辑)、控制流(`if`、`for`、`while`、`switch`)以及函数和闭包的使用。通过这些基础知识的学习,可以帮助初学者快速上手Swift。
64 1
|
6月前
|
安全 Swift iOS开发
swift语法
swift语法
54 1
|
6月前
|
Swift
Swift语言的语法
Swift语言的语法
62 2
|
6月前
|
大数据 Scala
大数据生态思维导图____2021最新最全Scala语法思维导图!(待更新)
大数据生态思维导图____2021最新最全Scala语法思维导图!(待更新)
54 0
|
Java Scala C++
Scala选择和循环语法
Scala选择和循环语法
54 0
|
分布式计算 Java Scala
一天学完spark的Scala基础语法教程十二、异常处理(idea版本)
一天学完spark的Scala基础语法教程十二、异常处理(idea版本)
200 0
一天学完spark的Scala基础语法教程十二、异常处理(idea版本)
|
JavaScript API Swift
深入浅出Swift(1)——基础语法
深入浅出Swift(1)——基础语法
105 0
|
前端开发 JavaScript Go
2022 软件工程师状况报告:Go 最抢手|开发者最“嫌弃” PHP、Swift、Scala/R/Objective-C
2022 软件工程师状况报告:Go 最抢手|开发者最“嫌弃” PHP、Swift、Scala/R/Objective-C
185 0
2022 软件工程师状况报告:Go 最抢手|开发者最“嫌弃” PHP、Swift、Scala/R/Objective-C