Open qtg2015sclt opened 8 years ago
switch wavelength {
case 380...450:
color = "violet"
case 451...495:
color = "blue"
case 496...570:
color = "green"
case 571...590:
color = "yellow"
case 621...750:
color = "red"
default:
color = "not visible"
}
let number = 5
var description = "\(number) is"
switch number {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += "a prime number, and also"
fall through
default:
description += "an integer."
}
//打印"5 is a prime number, and also an integer."
let myTuple = ("Question 1", false, false, true)
print(myTuple.0) // print "Question 1"
print(myTuple.3) // print true
//使用var关键字:
func incrementNumber(var number:Int){
number += 1
}
var aNumber = 5
incrementNumber(aNumber)
//此时aNumber为5
//使用inout关键字:
func incrementNumber(inout number:Int){
number += 1
}
var aNumber = 5
incrementNumber(&aNumber)
//此时aNumber为6
var animal = "octopus"
for character in animal.characters {
if character == "o" {
print("O")
} else {
print("\(character)")
}
}//OctOpus
var forwardString = "spoons"
var charactersReversed = forwardString.characters.reverse()
var backwardString = String(charactersReversed)
var nWithTilde = "\u{006F}\u{0301}"
nWithTilde.unicodeScalars.count
nWithTilde.characters.count
// Concatenation
let theTruth = "Money can't buy me love"
let alsoTrue = "but it can buy me a boat."
let combinedTruths = theTruth + ", " + alsoTrue
// Finding a substring within a string
var word = "fortunate"
word.containsString("tuna")
// Replacing a substring
var password = "Mary had a little loris"
var newPassword = password.stringByReplacingOccurrencesOfString("a", withString: "A")
var z: Int?
var str: String
str = "123"
z = Int(str)
z! * 2
var zee: Int?
let strings = ["ABC","123"]
let randomIndex = Int(arc4random() % 2)
let anotherString = strings[randomIndex]
zee = Int(anotherString)
if let intValue = zee {
intValue * 2
} else {
"No value"
}
//for-in循环的例子
for _ in 1...3 {
print("Three cheers for Swift!")
}
for c in "Oh hi, doggie 🐕".characters {
print(c)
}
import Foundation
var i=1
while (i < 1000) {
i += i
}
print(i)
var dieRoll1:Int = 2
var dieRoll2:Int = 2
while (!(dieRoll1 == 1 && dieRoll2 == 1)) {
dieRoll1 = Int(arc4random() % 6) + 1
dieRoll2 = Int(arc4random() % 6) + 1
print("\(dieRoll1), \(dieRoll2)")
}
while (true) {
var dieRoll1 = Int(arc4random() % 6) + 1
var dieRoll2 = Int(arc4random() % 6) + 1
print("\(dieRoll1), \(dieRoll2)")
if dieRoll1 == 1 && dieRoll2 == 1 {
break
}//只要到达break关键字,循环立刻停止,不会执行其他任何工作
}
var favoriteThings = ["raindrops on roses", "whiskers on kittens", "bright copper kettles", "raindrops on roses"]
//1:
var numbers = Array<Double>()
//2:
var moreNumbers = [Double]()
//3:
let differentNumbers = [97.5, 98.5, 99.0]
// An array can hold any type, but all of its items must be of the same type.
struct LightSwitch {
var on: Bool = true
}
var circuit = [LightSwitch]()
var livingRoomSwitch = LightSwitch()
var kitchenSwitch = LightSwitch()
var bathroomSwitch = LightSwitch()
circuit = [livingRoomSwitch, kitchenSwitch, bathroomSwitch]
var musicians = ["Neil Young","Kendrick Lamar","Flo Rida", "Fetty Wap"]
musicians.append("Rae Sremmurd")
musicians.insert("Dej Loaf", atIndex: 2)
musicians.removeAtIndex(3)
musicians
musicians.count
let musician = musicians[2]
// Array concatenation is super convenient in Swift.
var moreNumbers = [85.0, 90.0, 95.0]
let differentNumbers = [97.5, 98.5, 99.0]
moreNumbers += differentNumbers
// Arrays are value types; they are copied by value.
var array = ["same", "same", "same"]
var arrayCopy = array
arrayCopy[2] = "different"
arrayCopy
// Example: Finding the sum of all the Ints in an array
let intArray = [7, 21, 25, 13, 1]
var sum = 0
for value in intArray {
sum += value
}
//Example: Looping through the characters in a string
var romanticString = "How do I love thee? Let me count the ways."
var romanticStringWithKisses = ""
for character in romanticString.characters {
if character == "o" {
romanticStringWithKisses.append(Character("💋"))
} else {
romanticStringWithKisses.append(character)
}
}
1.234f // a float constant
2.2L // a long double constant
TBC...
数组
long totals[500] = {0};
字符串
cout << "I'd give my right ar"
"m to be a great violinist.\n";
每次读取一行字符串的输入:getline()(把输入队列的换行符丢弃、并在字符串尾添加空字符)和get()(把换行符保留在输入队列)
cin.getline(name, 20);
cin.getline(dessert, 20);
//1.用不带参数的cin.get()读取换行符【是的,可以读取换行符哟,原因:函数重载】:
cin.get(name, 20);
cin.get();
cin.get(dessert, 20);
//2.将两个类成员函数拼接起来:
cin.get(name, 20).get();
cin.get(dessert, 20).get();
//另外,cin.getline()也可以:
cin.getline(name, 20).getline(dessert, 20);
可拼接的原因:cin.get(name, 20)返回一个cin对象,该对象随后将被用来调用get()函数
- 区别:get检查错误简单,而getline使用起来简单
//1:
cin >> year;
cin.get();
//2:
(cin >> year).get();
string类
string str = "panther";
int len = str.size();
getline(cin, str); //而非cin.getline(str):C++的istream类早于string类引入,没有考虑string类
cin >> str; //但是可以这样用,使用的是string类的一个友元函数
for var i = 1; i < 11; i += 1 {
print(i)
}
for i in 1...8 {
for j in 1...8 {
if j % 2 == i % 2 {
print("⬛", terminator: "")
} else {
print("◻️", terminator: "")
}
}
print("")
}
for value in importantNumbersArray {
if let myValue = value where myValue == 3.14159 {
print(“Would you like a slice of pi?”)
}
}
// A dictionary is an unordered collection of key-value pairs
var phoneNumbers = ["Jenny": "867-5309", "Mateo": "510-7752", "Mike": "330-8004", "Alicia": "489-4608", "Daniel": "455-2626", "Josie": "769-3339"]
phoneNumbers["Alicia"]
// Initializer syntax
var groupsDict = [String:String]()
// Dictionary literal
var animalGroupsDict = ["whales":"pod", "geese":"flock", "lions": "pride"]
// Another example
var lifeSpanDict = ["African Grey Parrot": 50...70, "Tiger Salamander": 12...15, "Bottlenose Dolphin": 20...30]
var averageLifeSpanDict = [String:Range<Int>]()
var animalGroupsDict = ["whales":"pod", "geese":"flock", "lions": "pride"]
// Adding items to a dictionary
animalGroupsDict["crows"] = "murder"
animalGroupsDict["monkeys"] = "troop"
// The count method is available to all collections.
animalGroupsDict.count
print(animalGroupsDict)
// Removing items from a dictionary
animalGroupsDict["crows"] = nil
animalGroupsDict
// Updating a value
animalGroupsDict["monkeys"] = "barrel"
var group = animalGroupsDict.updateValue("gaggle", forKey: "geese")
group.dynamicType
print(animalGroupsDict)
animalGroupsDict.updateValue("crash", forKey:"rhinoceroses")
print(animalGroupsDict)
var oldValue = presidentialPetsDict.removeValueForKey("George Bush")
presidentialPetsDict["George W. Bush"] = oldValue
// 0-15 (given as binary literals)
let zero: UInt8 = 0b0000
let one: UInt8 = 0b0001
let fifteen: UInt8 = 0b1111
// 0-15 (given as hexidecimal literals)
let zeroHex: UInt8 = 0x0
let oneHex: UInt8 = 0x1
let nineHex: UInt8 = 0x9
let tenHex: UInt8 = 0xA
let elevenHex: UInt8 = 0xB
let tweleveHex: UInt8 = 0xC
let thirteenHex: UInt8 = 0xD
let fourteenHex: UInt8 = 0xE
let fifteenHex: UInt8 = 0xF
//这是一个特别好的例子:
struct UdacityStudent {
let name: String?
let username: String?
let userID: Int
}
// if a student's name is given, then use it
// otherwise, if a student's username is given, then use it
// otherwise, use the student's userID
func getDisplayName(student: UdacityStudent) -> String {
if let name = student.name {
return name
} else if let username = student.username {
return username
} else {
return String(student.userID)
}
}
// with the nil-coalesing operator, we can do this in one line!
func getDisplayNameNilCoalesing(student: UdacityStudent) -> String {
return student.name ?? student.username ?? String(student.userID)
}
let jarrod = UdacityStudent(name: "Jarrod", username: "jarrod", userID: 1)
let james = UdacityStudent(name: nil, username: "james", userID: 2)
let john = UdacityStudent(name: nil, username: nil, userID: 3)
getDisplayName(jarrod)
getDisplayNameNilCoalesing(jarrod)
getDisplayName(james)
getDisplayNameNilCoalesing(james)
getDisplayName(john)
getDisplayNameNilCoalesing(john)
//前缀运算符:
prefix operator ❗️ {}
prefix func ❗️ (word: String) -> String {
return "dis" + word
}
❗️"associate"
❗️"connect"
❗️"appear"
//中缀运算符:
infix operator ⊡ { associativity left precedence 155 }
func ⊡ (base: Int, power: Int) -> Int {
return Int(pow(Double(base), Double(power)))
}
5 ⊡ 2
5 ⊡ 2 ⊡ 2
//中缀运算符的另一个例子:
infix operator ♣︎ { associativity left precedence 155 }
func ♣︎ (from: Int, to: Int) -> Int {
var range: UInt32 = 0
if(from > to) {
range = UInt32((from - to) as Int)
} else {
range = UInt32((to - from) as Int)
}
let randomOffset = Int(arc4random_uniform(range + 1))
if(from > to) {
return to + randomOffset
} else {
return from + randomOffset
}
}
10 ♣︎ 3
1 ♣︎ 3
//后缀运算符:
postfix operator % {}
postfix func % (percent: Int) -> Double {
return (Double(percent) / 100)
}
50%
5%
200%
// Primary colors
enum PrimaryColor {
case Red
case Blue
case Yellow
}
enum Aunties {
case Aime, Billie, Diane, Gail, Janie, Pam
}
// The enum, MazeDirection, is assigned rawValues that are Ints.
enum MazeDirection: Int {
case Up = 0, Right, Down, Left //不写也可以,因为默认从0开始
}
// In Swift, raw values can be of type String or any of the numeric types.
enum AmericanLeagueWest: String {
case As = "Oakland"
case Astros = "Houston"
case Angels = "Los Angeles"
case Mariners = "Seattle"
case Rangers = "Arlington"
}
// Here, DrinkSize is assigned Int rawValues representing volume.
enum DrinkSize: Int {
case Small = 12
case Medium = 16
case Large = 20
}
// Here's how rawValues are accessed:
var message = "I hope the A's stay in \(AmericanLeagueWest.As.rawValue)"
var sugar = "A \(DrinkSize.Small.rawValue) oz Coke has 33 g of sugar."
// As you saw in the previous example, enums may be initialized by assigning a specific member of the enum to a variable or constant.
enum CaliforniaPark {
case Yosemite, DeathValley, Lasson, Sequoia
}
var destination = CaliforniaPark.Yosemite
// Enum types may also be initialized with rawValues.
enum MazeDirection: Int {
case Up = 0, Right, Down, Left
}
var currentDirection = MazeDirection(rawValue: 0)
enum AmericanLeagueWest: String {
case As = "Oakland"
case Astros = "Houston"
case Angels = "Los Angeles"
case Mariners = "Seattle"
case Rangers = "Arlington"
}
let myFavoriteTeam = AmericanLeagueWest(rawValue: "Oakland")
enum CaliforniaPark {
case Yosemite, DeathValley, Lasson, Sequoia
}
var warning = ""
var destination = CaliforniaPark.Yosemite
switch destination {
case .Yosemite:
warning = "Beware of aggressive bears!"
case .DeathValley:
warning = "Beware of dehydration!"
case .Lasson:
warning = "Watch out for boiling pools!"
case .Sequoia:
warning = "Watch out for falling trees!"
}
struct Student {
let name: String
var age: Int
var school: String
}
import Foundation
let studentPList = NSBundle.mainBundle().URLForResource("Students", withExtension: "plist")!
let studentArray = NSArray(contentsOfURL: studentPList)!
//: This code uses the array of dictionaries (studentArray) to create an array of Student structs called studentStructs.
var studentStructs = [Student]()
// must cast the values into most appropriate type
for student in studentArray {
if let name = student["name"] as? String {
if let age = student["age"] as? Int {
if let school = student["school"] as? String {
studentStructs.append(Student(name: name, age: age, school: school))
}
}
}
}
//: Once we've parsed the PList and created our structs we can use them more efficiently
for student in studentStructs {
print("\(student.name) is \(student.age) years old and attends the \(student.school).")
import UIKit
let mazeJSONURL = NSBundle.mainBundle().URLForResource("Maze1", withExtension: "json")!
let rawMazeJSON = NSData(contentsOfURL: mazeJSONURL)!
var mazeDictionaryFromJSON: NSDictionary!
do {
mazeDictionaryFromJSON = try! NSJSONSerialization.JSONObjectWithData(rawMazeJSON, options: NSJSONReadingOptions()) as! NSDictionary
}
if let mazeDictionaryFromJSON = mazeDictionaryFromJSON {
visualizeMaze(mazeDictionaryFromJSON)
}
iOS应用开发入门课程的限免结束了……目前没有小钱钱继续上课,等以后吧。 -TBC-
(总结一下)
——————————2016-05-26更新——————————
根据情况动态更新