粗解 apple swift 语言

官方文档百度网盘地址:http://pan.baidu.com/s/1dD8DWrB


   答应过群友写这篇文章,下班之后就一定要写。

  1. 官方文档的一开始就展示了程序员新语言的入门必写的:hello, world!只不过它是这样写的:

   println("Hello, world")

   为什么要抛弃main函数和分号?不习惯的说。apple说这样写类似于C和OC,但我总觉得类似java的System.out.println("something"); 你觉得呢?


  2.Simple Values

  var myVariable = 42
  let myConstant = 42


  let是常量,而var是变量。那么此处的let是不是可以理解为 int const a =  42 ?这是不指定类型的语法,需要指定类型可以这样 let:int = 42;

 

 3.字符转换

  let width = 94
  let widthLabel = label + String(width)

  从这两行代码中看到了JAVA的 valueOf的感觉。终于不用再写这么长了,解放了劳动力。[NSString stringWithFormat:@"%d",123];


官方例子如下:

 let apples = 3
 let oranges = 5
 let appleSummary = "I have \(apples) apples."
 let fruitSummary = "I have \(apples + oranges) pieces of fruit."

4. array and dictionary

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations”

最后这行我没看懂,只是赋值吗?谁能解释一下?


新建空字典和数组

let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

如果知道是什么类型,可以用[]声明空数组,用[:]声明空字典。

后边为什么要跟括号?


“If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.”

苹果的解释还是不太明白。


5.Control Flow

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    

   if score > 50

      teamScore += 3

   else

      teamScore += 1

}
teamScore
我熟悉的if (a == a),apple在不断的节约开发时间。最后一行跟了一局teamScore,至今不明白。


var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

if 还能这样写if(int a =8)???牛掰!


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."
}

  这么看起来简练多了。


6. Function

func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")

放眼望去,满是Lua的感觉。

如果参数不确定可以这样:func sumOf(numbers: Int...);

牛掰的是学人家closure

func a()

{

       func b()

       {

       }

}

闭包:

“numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result
    })”
不了解闭包的可以先去看看JS和Lua对闭包closure的解释。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值