iOS DeveloperiOS 开发 iOS进阶指南

Swift学习笔记(一)

2016-06-24  本文已影响75人  Originalee

简单记录学习Swift的笔记

简单值

例如

let label = "The width is"
let width = 94
let widthLabel = label + String(width)
let firstWord = "Lin"
let secondWord = "i love \(firstWord)"
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1]

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

let emptyArray = [String]()
let emptyDictionary = [String: String]()

shoppingList = []
occupations = [:]

控制流

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)

var optionalString: String? = "Hello"
print(optionalString == nil)

var optionalName: String? = "Lin"
var greeting = "Hello!"

optionalName = nil
if optionalName == nil {
   greeting = "Lix love Lin 🙄"
}else{
    let name = optionalName
    greeting = "\(name) love Lix 🌚"
}

let nickName: String? = "球球 🤗"
let fullName: String? = "LinHong"
let informalGreeting = "Hi \(nickName ?? fullName)"

let sport = "basketball"
switch sport {
case "football":
    print("this is the first sport")
    
case "running":
    print("Lin was running everyday")
    
case let x where x.hasSuffix("ball"):
    print("Lix play \(sport) everyday")
    
default:
    print("keep moving")
}

let interestingNumbers = [
    "Prime": [2,3,5,7,11],
    "Fibonacci": [1,1,2,3,5,8,13],
    "Square": [1,4,9,16]
]

var largest = 0
var numberClass = "number"
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            numberClass = kind
        }
    }
}

print(largest)
print(numberClass)

var n = 2
while n < 100 {
    n = n * 2
}
print(n)

var m = 2
repeat {
 m = m * 2
} while m < 100     //循环条件可以在结尾,至少保证循环一次
print(m)

var total = 0
for i in 0..<4 {
    total += i
}
print(total)

var total = 0
for i in 0...100 {
    total += i
}
print(total)

上一篇 下一篇

猜你喜欢

热点阅读