Swift 学习(一)

Swift 学习(一),第1张

概述国外开发者最近发现,WWDC2014上苹果发布的新语言Swift,和古老的  Scala 语言在语法上存在众多的相似之处。    本文以苹果官方教程  The Swift Programming Language 中的示例,比较Swift与Scala两种语言实现同一功能的代码。  Swift语言从语法上来看,几乎是Scala的一个分支,在以下功能上几乎是等同的:类型继承、闭包、元组(Tuple)、

国外开发者最近发现,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()
变量与常量
// Swiftvar myVariable = 42myVariable = 50let myConstant = 42// Scalavar myVariable = 50val myConstant = 42
显式类型
// Swiftlet explicitDouble: Double = 70// Scalaval explicitDouble: Double = 70
强制类型转换
// Swiftlet label = "The wIDth is "let wIDth = 94let wIDthLabel = label + String(wIDth)//Scalaval label = "The wIDth is "val wIDth = 94val wIDthLabel = label + wIDth
字符串数据填充
// Swiftlet apples = 3let oranges = 5let fruitSummary = "I have \(apples + oranges) " +  "pIEces of fruit."// Scalaval apples = 3val oranges = 5val fruitSummary = s"I have ${apples + oranges} " + " pIEces of fruit."
整数半开区间运算符
// Swiftlet names = ["Anna","Alex",68)">"Brian",68)">"Jack"]let count = names.countfor 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// Scalaval names = Array("Jack")val count = names.lengthfor (i <- 0 until count) { println(s"Person ${i + 1} is called ${names(i)}")}// Person 4 is called Jack
整数闭区间运算符
// Swiftfor 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// Scalafor (index <- 1 to 5) { println(s"$index times 5 is ${index * 5}")}// 5 times 5 is 25
集合 数组
// Swiftvar shopPingList = ["catfish",68)">"water", "tulips",68)">"blue paint"]shopPingList[1] = "bottle of water"// Scalavar shopPingList = Array("blue paint")shopPingList(1) = "bottle of water"
字典
// Swiftvar occupations = [ "Malcolm": "Captain",68)">"Kaylee": "Mechanic",]occupations["Jayne"] = "Public Relations"// Scalavar occupations = scala.collection.mutable.Map( "Malcolm" -> "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 { return "Hello \(name),today is \(day)."}greet("Bob",68)">"Tuesday")// Scaladef greet(name: String,day: String): String = { return s"Hello $name,today is $day."}greet("Tuesday")
元组(Tuple)返回值
// Swiftfunc getGasPrices() -> (Double,Double,Double) { return (3.59,3.69,153)">3.79)}// Scaladef getGasPrices(): (Double,Double) = { return (3.79)}
可变数量参数
// Swiftfunc sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers {  sum += number } return sum}sumOf(42,153)">597,153)">12)// Scaladef sumOf(numbers: Int*): Int = { var sum = 0 for (number <- numbers) {  sum += number } return sum}sumOf(12)
函数作为数据类型
// Swiftfunc makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int {  return 1 + number } return addOne}var increment = makeIncrementer()increment(7)// Scaladef makeIncrementer(): Int => Int = { def addOne(number: Int): Int = {  return 7)
集合迭代器(Map)
// Swiftvar numbers = [20,153)">19,153)">7,153)">12]numbers.map({ number in 3 * number })// Scalavar numbers = Array(12)numbers.map( number => 3 * number )
排序
// Swiftsort([1,153)">5,153)">3,153)">12,153)">2]) { $0 > $1 }// ScalaArray(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)
类 定义
// Swiftclass @H_359_502@Shape { var numberOfSIDes = 0 func simpleDescription() -> String {  return "A shape with \(numberOfSIDes) sIDes." }}// Scala0 def simpleDescription(): String = {  return 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 = 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()// Scalaclass 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()
检查实例所属的类
// Swiftvar movIECount = 0var songCount = 0for item in library { if item is MovIE {  ++movIECount } else if item is Song {  ++songCount }}// Scalavar movIECount = 0for (item <- library) { if (item.isinstanceOf[MovIE]) {  movIECount += 1 } else if (item.isinstanceOf[Song]) {  songCount += 1 }}
基类转派生类(向下转换)
// Swiftfor object in someObjects { let movIE = object as MovIE println("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<@H_359_502@T: nameable>(x: T) { println("name is " + x.name())}// Scalatrait nameable { def name(): String}def f[T <@H_359_502@: nameable](x: T) = {  println("name is " + 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 / .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")// prints "Three feet is 0.914399970739201 meters"// Scalaobject 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.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"
总结

以上是内存溢出为你收集整理的Swift 学习(一)全部内容,希望文章能够帮你解决Swift 学习(一)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1088842.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存