花半个小时看了一下 Swift 的文档,很开心地发现不需要学习它的语法,各位熟悉 ruby 语法的程序员就算不看文档,阅读 swift 代码也应该毫无压力,如果你之前熟悉 apple framework 的各种 api,那就赶紧转移到 swift 开发 ios 应用吧,因为终于可以抛弃 Objective C 这个上世纪的语言了 :)
swift 和 ruby 几个简单的对比:
swift 用 let 定义常量,用 var 定义变量 swift
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
ruby 无关键字,用大写字母代表常量 ruby
MAXIMUM_NUMBER_OF_LOGIN_ATTEMPTS = 10
currentLoginAttempt = 0
定义多个变量 swift
var x = 0.0, y = 0.0, z = 0.0
ruby
x, y, z = 0.0, 0.0, 0.0
字符串 swift
println("The current value of friendlyWelcome is \(friendlyWelcome)")
ruby
p "The current value of friendlyWelcome is #{friendlyWelcome}"
N 进制数字和各种数字格式,完全和 ruby 是一模一样... swift
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
Tuples, swift 需要定义类型组合,常用在多参数返回,而 ruby 则直接支持数组 swift
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
let (justTheStatusCode, _) = http404Error
ruby
http404Error = [404, "Not Found"]
statusCode, statusMessage = http404Error
justTheStatusCode , _ = http404Error
条件绑定,这个很方便的语法糖,已经成为现代语言的标配: swift
if let actualNumber = possibleNumber.toInt() {
println("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
ruby
if actualNumber = possibleNumber.toInt
p "#{possibleNumber} has an integer value of #{actualNumber}"
else
p "#{possibleNumber} could not be converted to an integer"
end
遍历数组 swift
for item in shoppingList {
println(item)
}
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
ruby
for item in shoppingList
p item
end
#ruby的数组是Enumerable,遍历更常用each/each_with_index等方法
shoppingList.each_with_index{|value, index| p "Item #{index + 1}: #{value}"}
Dictionary swift
var airports = ["TYO": "Tokyo", "DUB": "Dublin"]
airports["LHR"] = "London"
for (airportCode, airportName) in airports {
println("\(airportCode): \(airportName)")
}
ruby
airports = {TYO: "Tokyo", DUB: "Dublin"}
airports[:LHR] = "London"
airports.each{|airportCode, airportName| p "#{airportCode}: #{airportName}" }
Range swift
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
Ruby 用..表示闭合区间,...表示开合区间 ruby
(1..5).each{|index| p "#{index} times 5 is #{index * 5}"}
Closures swift
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {
(var number) -> String in
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
// strings is inferred to be of type String[]
// its value is ["OneSix", "FiveEight", "FiveOneZero"]
ruby
digitNames = {
0 => "Zero", 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four",
5 => "Five", 6 => "Six", 7 => "Seven", 8 => "Eight", 9 => "Nine"
}
numbers = [16, 58, 510]
numbers.map do |number|
output = ""
while number > 0
output = digitNames[number % 10] + output
number /= 10
end
output
end
灵活的 switch
Swift 中的 switch 支持各种各样的比较操作:
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
其中的 case let x where x.hasSuffix("pepper"):
ruby 怎么实现?
c++
class A : Base {
A() { ... }
}
swift
class A : Base {
init() { ... }
}
python
a_new_instance = AClass()
swift
var a_new_instance = AClass()
groovy
foo.?bar
swift
foo?.bar
a?[3]
scala
case class Ace
swift
enum Rank: Int {
case Ace = 1
}
C#
public int Month {
get {
return month;
}
set {
month = value;
}
}
swift
var Month : Int {
get {
return month
}
set {
month = newValue
}
}
c++
template <T>
void generic_func(T t) {
}
swift
func generic_func<T>(T t) {
}
objc protocol and category swift protocol and extension
c# out param, c++ reference
swift inout
好吧,仅针对语言来评价,不知道为什么 Apple 不更好的支持 Ruby, 而整出了这么个语言....
可能我这些年只学了个 Ruby 的缘故吧,看其他 新出的
语言,都觉得不伦不类的。呵呵
@quakewang
``actualNumber = possibleNumber.toInt
这里是不是写错了?
好吧,仅针对语言来评价,不知道为什么 Apple 不更好的支持 Ruby, 而整出了这么个语言....
可能我这些年只学了个 Ruby 的缘故吧,看其他 新出的
语言,都觉得不伦不类的。呵呵
@quakewang
``actualNumber = possibleNumber.toInt
这里是不是写错了?
熟悉 ruby 的前辈能留个更方便的联系方式吗?最近在研究 redmine
是用 ruby 开发的,在搭建 ruby 开发环境时报了好多错误,望高手指点。
"8116"
C:/Bitnami/redmine-2.5.0-0/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in require': cannot load such file -- initializer (LoadError)
from C:/Bitnami/redmine-2.5.0-0/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in
rescue in require'
from C:/Bitnami/redmine-2.5.0-0/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in require'
from C:/Users/chenaq/My Documents/Aptana RadRails Workspace/redmine/vendor/bundle/ruby/1.9.1/gems/thin-1.3.1/spec/rails_app/config/boot.rb:54:in
load_initializer'
from C:/Users/chenaq/My Documents/Aptana RadRails Workspace/redmine/vendor/bundle/ruby/1.9.1/gems/thin-1.3.1/spec/rails_app/config/boot.rb:39:in run'
from C:/Users/chenaq/My Documents/Aptana RadRails Workspace/redmine/vendor/bundle/ruby/1.9.1/gems/thin-1.3.1/spec/rails_app/config/boot.rb:11:in
boot!'
from C:/Users/chenaq/My Documents/Aptana RadRails Workspace/redmine/vendor/bundle/ruby/1.9.1/gems/thin-1.3.1/spec/rails_app/config/boot.rb:109:in <top (required)>'
from C:/Bitnami/redmine-2.5.0-0/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in
require'
from C:/Bitnami/redmine-2.5.0-0/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in require'
from C:/Users/chenaq/My Documents/Aptana RadRails Workspace/redmine/vendor/bundle/ruby/1.9.1/gems/thin-1.3.1/spec/rails_app/script/server:2:in
'
from -e:2:in load'
from -e:2:in