与oc相比更简洁,编译时的检错机制更完善
var myVariable = 42
myVariable = 50
let myConstant = 42
let myString = "Hello World"
print(myString);//;加不加都可以,不会报错
let mStr = "Hello World"
let mString:String
print(mStr)
let isBool = true
print(isBool)
let width:Float = 4
print(width)
let lable = "The width is"
let width1 = 94
let labelWidth = lable + String(width1)
var widthLLabel = "lable \(width1)"
widthLLabel = lable+"\(width1)"
var shoplist = ["apple","oranges","chocolate",]
shoplist[0] = "cookie"
var occ = ["Mom":"Mama","Dad":"Baba"]
occ["Sister"] = "Jiejie";
print(occ)
shoplist.append("fruit")
print(shoplist)
var emptyArr = [String]()
var emptyDic = [String:Float]()
emptyArr = []
emptyDic = [:]
let `class` = "CSDN"
print(`class`)
//typealias newname = typeName
typealias Feet = Int
var optionInt:Optional<Int>
var myInt:Int? = 1
var opionSt:Optional<String>
var myStr:String? = nil;
let optionalStr:String? = ""
print(optionalStr == nil)
let nikename:String? = nil
let fullName = "John"
let informal = "Hi,\(nikename ?? fullName)"
print(informal)
myStr = "Hello Swift!";
if myStr != nil {
print(myStr ?? "")
}else{
print("myStr值为nil")
}
var optionArr:([Int])
var optionArr1:([String])
let a=1+2
let b = 2 + 3
//let m = 1+ 2会报错,swift会判定在1+之后语句结束。
print(a+b)
与oc相比更规范,语法要求更严格
let inScores = [60,70,80,100,12]
var teamScore = 0
for score in inScores {
if score>50 {
teamScore += 3
}else{
teamScore += 1
}
}
print(teamScore)
let optionalName:String? = nil
var greeting = "Hello!"
if let name=optionalName {
greeting = "hello,\(name)"
}else{
greeting = "hello,\(optionalName ?? "")"
}
print(greeting)
for x in a...b {
//terminator的含义是将换行符\n置为""(可以理解为使换行符消失)
print("\(x) ",terminator:"")
}
var total = 0
for i in 0..<4 {
total += i
}
print(total)
for x in 0..<array.count {
if x > 0 {
}
}
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
var largestKind = ""
for (kind,numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestKind = kind
}
}
}
print("largest is \(largest), largestKind is \(largestKind)")
let vegetable = "cucumber"
switch vegetable {
case "celery":
print("Add some raisins an make ants on a log.")
case "cucumber","watercress":
print("That woudle make a good sandwich.")
case let x where x.hasSuffix("pepper")://let将匹配常量的值赋给x
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup")
}
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)