首页 > 代码库 > Swift Basic
Swift Basic
推荐使用Xcode6 playground的功能来测试,可以很方便看到输出
不需要分号
println("Hello, world!")
简单的赋值方式
使用 let 标记一个常量 var 标记一个变量
var myVariable = 42 myVariable = 50 let myConstant = 42
追加声明数据类型
let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble: Double = 70
变量之间可以方便的转换类型
let label = "The width is " let width = 94 let widthLabel = label + String(width)
以 \(变量名) 的形式可以很方便的无视类型转换到String输出
let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit."
创建数组,字典
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 = [String: Float]()
流程控制
if , switch 做流程选择
for-in, for, while, do-while 做循环控制
let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore
好来分析一下下面的代码
//使用if和let来处理可能不存在的值 //在数据类型后面加?来标记可能不存在的值 var optionalString: String? = "Hello" optionalString == nil //如果optinalName 为nil 则执行else var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" }else{ greeting="The value is nil"}
//定义字典 let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { //取出字典里面的数字 for number in numbers { //挑选出最大的值 if number > largest { largest = number } } } largest //结果为25
for i in 0..<4
for var i = 0; i < 4; ++i
上面两个语句是等效的
------------------------------------------------
函数
Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate the parameter names and types from the function’s return type.
使用func定义一个函数
使用->设置函数返回数据类型
//传入参数2个String,返回一个String func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } //调用函数 greet("Li", "SUNDAY")
//传入参数是一个Int数组,函数功能算出这个数组的最大 最小 和值 func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { //初始化,将最小值,最大值定义到Int数组第一个值 var min = scores[0] var max = scores[0] var sum = 0 //遍历数组 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } //调用函数 let statistics = calculateStatistics([5, 3, 100, 3, 9]) statistics.sum statistics.2
Swift Basic
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。