最新消息:相关的技术文章和资料收集整理,感谢大家支持。

Apple Swift编程语言入门教程

iOS平台 djwangping 12244浏览

基本概念

Hello, world

类似于脚本语言,下面的代码即是一个完整的Swift程序。

println("Hello, world")

变量与常量

Swift使用var声明变量,let声明常量

var myVariable = 42
myVariable = 50
let myConstant = 42

类型推导

Swift支持类型推导(Type Inference),所以上面的代码不需指定类型,如果需要指定类型:

let explicitDouble : Double = 70

Swift不支持隐式类型转换(Implicitly casting),所以下面的代码需要显式类型转换(Explicitly casting):

let label = "The width is "
let width = 94
let width = label + String(width)

字符串格式化

Swift使用\(item)的形式进行字符串格式化:

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

数组和字典

Swift使用[]操作符声明数组(array)和字典(dictionary):

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

一般使用初始化器(initializer)语法创建空数组和空字典:

let emptyArray = String[]()
let emptyDictionary = Dictionary<string, float="">()

转载请注明:Mibugs.com » Apple Swift编程语言入门教程