转载

Swift 语法初窥(一)之基础

References: The Swift Programming Language

某程序员对书法十分感兴趣,退休后决定在这方面有所建树。于是花重金购买了上等的文房四宝。一日,饭后突生雅兴,一番磨墨拟纸,并点上了上好的檀香,颇有王羲之风范,又具颜真卿气势,定神片刻,泼墨挥毫,郑重地写下一行字: hello world

print("Hello, World")

Simple Values(简单值)

定义变量用 var ,常量用 let

var myVariable = 42
myVariable = 50
let myConstant = 42

常量只能赋值一次,不用必须在声明的时候去赋值。

编译器会自动推断常量和变量的类型,但是如果推断不出来(比如说没有初始值等),就需要声明类型。

let helloTalk : String
helloTalk = 1   // 会报错
helloTalk = "helloTalk"

Swift的值不会隐式被转为其他类型

let widthFloat = 93.33          // 自动推断 为 Double
let width : Int = widthFloat    // 把 Double 赋值给 Int,会报错
let widthLabel = label + String(width)

// 把值转换成字符串还可以这样: /(ValueName)
let widthString = "width: /(width)."

创建、定义一个数组或者字典

let emptyArray = [String]()
let emptyDictionary = [String: Float]()
// 或者
let emptyArray = []
let emptyDictionary = [:]

Control Flow(控制流)

for-in

let persons = ["person1","person2"]
for personString in persons {
  print(personString)
}
// 遍历字典
let dict = [
            "name" : "Joke",
            "age"  : 16
        ] as [String : Any]
        
for (key,value) in dict {
  print("/(key) : /(value)")
}

if-else

if 2>1 {
  print("2 大于 1")
}else{
  print("2 还是大于 1 啊")
}

if 后面必须是布尔表达式,如果是一个值的话不会隐式的与 0 比较。

switch

let vegetable = "red pepper"
switch vegetable {
case "celery":
  print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
  print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
  print("Is it a spicy /(x)?")
default:
  print("Everything tastes good in soup.")
}

switch 不仅支持基本数据类型。另外Swift中的 switch 语法可以省略 break 。但是不能省略 default ,会报 Switch must be exhaustive, consider adding a default clause 的编译错误。

while

var i = 1
while i<100 {
  i += 1
}
// 或者
var i = 1
repeat{
  i += 1
}while i < 100
原文  https://sanyucz.top/2016/10/05/swift1_basic_grammar/
正文到此结束
Loading...