标题: 初学swift基础 见识下语法 [打印本页] 作者: qq541955920 时间: 2014-8-18 07:40 标题: 初学swift基础 见识下语法 swift一些基础,ios课程会有,不会的先看看了解下一些基础语法
import Foundation
println("Hello, World!")
//赋值
let myVar:Float = 4
println(myVar)
//值的转换没有隐式转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
println(widthLabel)
//另一种将值装换为String的方式\()
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
let fruitPriceSumary = "This is String \(0.8), not float"
println(appleSummary + " " + fruitSummary + " " + fruitPriceSumary)
//使用[]创建数组或者字典,并访问
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
println(shoppingList[0..4])
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
println(occupations["Malcolm"])
println(occupations["Kaylee"])
println(occupations["Jayne"])
//空数字或者空字典
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
//for语句
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
println(teamScore)
//if语句
var optionalString: String? = "Hello"//类型后面?表示这个值是可选的
optionalString == nil//可以是nil或者具体值
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
} else {
greeting = "optionalName is NIL"
}
println(greeting)
//switch语句,default语句不可以少,也不需要在每个语句后面写break
let vegetable = "red pepper"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
println(vegetableComment)
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
println(vegetableComment)
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
println(vegetableComment)
default:
let vegetableComment = "Everything tastes good in soup."
println(vegetableComment)
}