编辑代码

// //Swift数组的创建
// //用中括号创建数组
// var studentArray=[String](arrayLiteral:"张三","李四","王五")
// print("studentArray:\(studentArray)")
// var fruitsArray=[String](repeating:"水果",count:3)
// print("fruitsArray:\(fruitsArray)")
// var teacherArray:[String]=["罗良夫","教师一","教师二"]
// print("teacherArray:\(teacherArray)")
// //用Array关键字创建数组
// var studentArray1=Array<String>(arrayLiteral:"孙六","李四","王无")
// print("studentArray1:\(studentArray1)")
// var teacherArray1:Array<String>=["孔子","庄子","孟子"]
// print("teacherArray1:\(teacherArray1)")
// //用字面值创建数组
// let Direction=["东","西"]
// print("Direction:\(Direction)")
// //用+运算符创建数组
// var namesArray=studentArray+studentArray1
// print("namesArray:\(namesArray)")

// //数组的常用操作
// var carBrand:Array<String>=["a1","a2","a3","a4","a5"]
// //访问数组
// print("carBrand[0]:\(carBrand[0])")
// //指定位置的数组元素
// print("carBrand中的第一个元素:\(carBrand.first!)")
// //添加数组元素
// carBrand+=["a6","a7"]
// print("+=添加多个元素:\(carBrand)")


// //break语句
// //计算1000以内能被3和7整除的数
// var num=1 , count=0
// while num < 1000{
//     if num % 3 == 0 && num % 7 == 0{
//         count += 1
//         print(count,num,separator:":")
//     }
//     if count == 5{
//         break
//     }
//     num += 1
// }
// //输入一个数,输出1到这个数的范围
// var num:Int?
// let s = readLine()
// num = Int(s!)
// print("1到\(num!)的范围奇数:",terminator:"")
// for i in 1...num!{
//     if i % 2 == 0{
//         continue
//     }
//     if i == num! || i == num! - 1{
//         print(i,terminator:".")
//     }else{
//         print(i,terminator:",")
//     }
// }

var animalArray=[String]()
if animalArray.isEmpty{
    print("animalArray is empty!")
}
animalArray.append("tiger")
animalArray.append("lion")
print("animalArray\(animalArray)")
//数据的初始化2
var oneBitNumberArray:Array<Int>=[0,1,2,3,4,5,6,7,8,9]
var botanyArray1:[String]=["rosemary","parsley","sage","thyme"]
var botanyArray2=["rosemary","parsley","sage","thyme"]
print("There are \(botanyArray1.count) kinds of botany")
//数组的初始化3
var twoBitNumberArray=[Int](repeating:0,count:6)
var threeBitNumberArray=[Int](repeating:11,count:3)
//数组的相加
var theAddedNumberArray = twoBitNumberArray + threeBitNumberArray
//数组的累加
animalArray += ["hawk"]
animalArray += ["sheep","horse"]
print("animalArray\(animalArray)")
//数组的下标操作
var theFirstAnimal = animalArray[0]
animalArray[1] = "hen"
animalArray[2...4] = ["goat","rat","cock","rabbit"]
print(animalArray)
//数组插入元素
animalArray.insert("snake",at:3)
print("animalArray\(animalArray)")
//数组删除元素
animalArray.removeFirst()
print("animalArray\(animalArray)")
animalArray.removeLast()
print("animalArray\(animalArray)")
animalArray.remove(at:2)
print("animalArray\(animalArray)")
//数组的遍历
for animal in animalArray{
    print(animal,terminator:"")
}
print()
for (index,animal) in animalArray.enumerated(){
    print("No.\(index) animal is \(animal)")
}
print(animalArray)

//数组片段
var animalArray:[String]=["hen","goat","rat","cock"]
let myZoo = animalArray[1...2]
print(myZoo)
myZoo[1]
myZoo[2]
//myZoo[0]
//将数组片段转换成数组类型
let newZoo = Array(animalArray[1...2])
print(newZoo)
newZoo[0]
newZoo[1]
//判断数组是否包含指定元素
animalArray[1...3].contains("hen")
animalArray.contains("hen")
print("animalArray\(animalArray)")
//数组交换元素位置
animalArray.swapAt(2,3)
print("animalArray\(animalArray)")
//数组排序
animalArray.sort()
print("animalArray\(animalArray)")

//练习
var majorCompulsoryCourse = [String]()
majorCompulsoryCourse.append("Data Structure")
majorCompulsoryCourse.append("Computer Organizagtion")
majorCompulsoryCourse.append("Computer Networks")
print("majorCompulsoryCourse\(majorCompulsoryCourse)")

var specializedOptionCourse = ["Ios app development","Swift Programming","Artifical Intelligence"]
print("specializedOptionCourse\(specializedOptionCourse)")

var generalKnowledgeCourse=[String](repeating:"Music",count:3)
print("generalKnowledgeCourse\(generalKnowledgeCourse)")
generalKnowledgeCourse[1]="Painting"
generalKnowledgeCourse[2]="Literature"
print("generalKnowledgeCourse\(generalKnowledgeCourse)")

var allBookedCourse = majorCompulsoryCourse + specializedOptionCourse + generalKnowledgeCourse
print("allBookedCourse\(allBookedCourse)")

majorCompulsoryCourse[0] = "Discrete Mathematics"
specializedOptionCourse.insert("Experiment of Mobile Application Development",at:3)
generalKnowledgeCourse.remove(at:1)
allBookedCourse = majorCompulsoryCourse + specializedOptionCourse + generalKnowledgeCourse
print("allBookedCourse\(allBookedCourse)")
for(index,course) in allBookedCourse.enumerated(){
    print("No.\(index) course is \(course)")
}

let sliceOfAllBookedCourse = allBookedCourse[3...6]
var newArrayFromSlice = Array(sliceOfAllBookedCourse)
print("newArrayFromSlice\(newArrayFromSlice)")

newArrayFromSlice.swapAt(0, 3)
newArrayFromSlice.sort()
if newArrayFromSlice.contains("Swift Programming") {
    print("It contains course: Swift Prgramming")
} else {
    print("No course: Swift Programming")
}
if newArrayFromSlice.contains("Swift") {
    print("It contains course: Swift")
} else {
    print("No course: Swift")
}
//2.集合
//集合的初始化1
var weatherOfSanya = Set<String>()
weatherOfSanya = ["rainy","sunny","stormy"]
//集合的初始化2
var weatherOfBj:Set = ["dry","windy","frogy","sunny"]
//判断集合是否为空
if weatherOfSanya.isEmpty{
    print("The set of weather is empty!")
}else{
    print("There are \(weatherOfBj.count) kinds weather!")
}
//集合插入元素
weatherOfSanya.insert("cloudy")
//集合删除元素
weatherOfSanya.remove("stormy")
weatherOfSanya.remove("dry")
//删除集合所有元素
//weatherOfSanya.removeAll()
//检索特定元素
if weatherOfSanya.contains("sunny") {
    print("Sanya is sunny sometimes.")
}
//遍历集合
for weather in weatherOfSanya {
    print("\(weather)")
}
//集合排序
print("the result of unsorted : ")
for weather in weatherOfSanya {
    print("\(weather)")
}
print("the result of sorted : ")
for weather in weatherOfSanya.sorted() {
    print("\(weather)")
}
//集合交集运算
weatherOfBj.intersection(weatherOfSanya)
//集合并集运算
weatherOfBj.union(weatherOfSanya)
//集合差集运算
weatherOfBj.subtract(weatherOfSanya)

//练习
var gradeOfTheory = Set<String>()
if gradeOfTheory.isEmpty {
    gradeOfTheory.insert("Fail")
    gradeOfTheory.insert("Pass")
    gradeOfTheory.insert("Common")
    gradeOfTheory.insert("Good")
    gradeOfTheory.insert("Excellent")
} else {
    print("Grade Set of Theory is not empty!")
}

var gradeOfExperiment: Set = gradeOfTheory
gradeOfExperiment.remove("Common")
gradeOfExperiment.remove("Good")
gradeOfExperiment.remove("Excellent")
if gradeOfExperiment.contains("Fail") && gradeOfExperiment.contains("Pass") {
    print("Grade Set of Experiment has two levels: Fail and Pass.")
} else {
    print("Grade Set of Experiment is lack of Fail or Pass level!")
}
print("All grades in Theory are: ")
for grade in gradeOfTheory {
    print("\(grade) ",terminator:"\t")
}
print("\nAll grades in Experiment are: ")
for grade in gradeOfExperiment {
    print("\(grade) ",terminator:"\t")
}
gradeOfTheory.sorted()
print("\nAll SORTED grades in Theory are: ")
for grade in gradeOfTheory {
    print("\(grade) ",terminator:"\t")
}
gradeOfExperiment.sorted()
print("\nAll SORTED grades in Experiment are: ")
for grade in gradeOfExperiment {
    print("\(grade) ",terminator:"\t")
}
print("\nIntersection results are: ")
for grade in gradeOfTheory.intersection(gradeOfExperiment) {
    print("\(grade)",terminator:"\t")
}
print("\nUnion results are: ")
for grade in gradeOfTheory.union(gradeOfExperiment) {
    print("\(grade)",terminator:"\t")
}
print("\nSubtract results are: ")
for grade in gradeOfTheory.subtracting(gradeOfExperiment) {
    print("\(grade)",terminator:"\t")
}
//3.字典
//声明字典
var ascIIDictChar0 = Dictionary<Int, Character>()
var ascIIDictNum0 = [Int:Int]()
//初始化字典
var ascIIDictChar = [97:"a",98:"b",99:"c",100:"d",101:"e",102:"f"]
var ascIIDictNum = [32:0,33:1,34:2,35:3,36:4,37:5,38:6]
//设置字典的容量
ascIIDictNum.reserveCapacity(10)
//修改字典元素值方法1
ascIIDictChar[103] = "g"//添加元素
print(ascIIDictChar)
ascIIDictChar[97] = "A"
//修改字典元素值方法2
print(ascIIDictChar)
if let originValue = ascIIDictChar.updateValue("a", forKey: 97) {
    print("The origin value is \(originValue)")
}
print(ascIIDictChar)
//删除字典元素值方法1
ascIIDictChar[97] = nil
print(ascIIDictChar)
//删除字典元素值方法2
if let removedValue = ascIIDictChar.removeValue(forKey: 98){
    print("Value \(removedValue) is removed.")
}
//遍历字典键值对
for (ascIICode,char) in ascIIDictChar {
    print("ascII code \(ascIICode) express char \(char) ")
}
//遍历字典键集合
for ascIICode in ascIIDictChar.keys {
    print("keys:\(ascIICode);", terminator:"  ")
}
print()
//遍历字典值集合
for char in ascIIDictChar.values {
    print("chars:\(char);", terminator:"  ")
}
//字典keys属性
let ascIICodeArray = Array(ascIIDictChar.keys)
//字典values属性
let charArray = Array(ascIIDictChar.values)

//练习
var schoolOfUniversity = [Int:String]()
schoolOfUniversity = [1:"Material", 2:"Electronics", 3: "Astronics", 4:"Dynamics", 5:"Aircraft", 6:"Computer"]
schoolOfUniversity[3] = "revisedSchool"
schoolOfUniversity.updateValue("updatedSchool", forKey: 4)
print(schoolOfUniversity)
schoolOfUniversity[7] = "Mechanism"
schoolOfUniversity[8] = "Management"
print(schoolOfUniversity)
print("Elements in Dictionary are as below:")
for (code, schoolName) in schoolOfUniversity {
    print("Code:\(code)---School Name:\(schoolName)")
}
var codeForSchool = Array(schoolOfUniversity.keys)
var schoolName = Array(schoolOfUniversity.values)
print("All codes are: ")
for code in codeForSchool {
    print("\(code )", terminator: "  ")
}
print("\nAll school name are:")
for name in schoolName {
    print("\(name) ", terminator: " ")
}
//4.fallthrough的功能
//fallthrough的功能
var index = 10
switch index {
case 100  :
      print( "index 的值为 100")
      fallthrough
   case 10,15  :
      print( "index 的值为 10 或 15")
      fallthrough
   case 5  :
      print( "index 的值为 5")
   default :
      print( "默认 case")
}
//fallthrough的使用
var score=70
var member=true
switch(score){
    case 0..<60:
        print("遗憾未中奖!")
        if(member==true){
            fallthrough
        }
    case 9999:print("会员额外赠送金币1万!")
    case 60...70:
        print("三等奖!")
        if(member==true){
            fallthrough
        }
    case 9999:print("会员额外赠送金币10万!")
    default:print(0)
}
//5.forloop标签的功能
//forloop的功能
    var i,j:Int
    var s:Int
    
    forloop:for i in 1...3 {
        for j in 1...3 {
            s = i*j
            print("i*j=\(s)")
            if (s>5) {
                print("i*j>50,退出外循环");
                break forloop
            }
   }
}
//forloop的使用
loop1:for i in 1...3{
    loop2:for j in 1...3{
        print("i=\(i),j=\(j)")
        if(j==i){
            break loop2
        }
    }
    if(i==3){
        break loop1
    }
}
//6字符串的定义方式
//字符的定义
let characterAlphabet:Character = "a"
let characterNumber:Character = "9"
let characterOperator:Character = "*"
//多行文本的定义
let multilinesString = """
Do the most simple people,
the most happy way:
We often heart will feel tired,just want to too much;
We always say life trival,is actually I don't understand taste;
Our business is busy , often is not satisfied;
We are always competitive , is actually his vanity is too strong.
Don't compare , heart is coll , life is so simple.
"""
print(multilinesString)

//字符串变量定义
var emptyStr = ""
var anotherEmptyStr = String()
if emptyStr.isEmpty {
    print("This String is empty")
}
var str1 = "hello world"
var str2 = str1
print(str2)
str2 = "helllo China"
print(str2)

//练习
var schoolName = ""
var universityName = String()
if schoolName.isEmpty {
    print("School Name is empty!")
} else {
    print("My School is \(schoolName)")
}
universityName = "Beijing University of Aeronautic and Astronautic"
if universityName.isEmpty {
    print("University Name is empty!")
} else {
    print("My University is \(universityName)")
}
var myUniversity = ""
myUniversity = universityName
print("My university is \(myUniversity), University Name is \(universityName)")
myUniversity = "Tsinghua University"
print("My university is \(myUniversity), University Name is \(universityName)")
//7.	字符串的操作
//7 字符串的操作
let theString = "It's my world!"
//字符串大写
let upString=theString.uppercased()
print("the uppercaseString is \(upString)")
//字符串小写
let lowString=theString.lowercased()
print("the lowercasesSteing is \(lowString)")

//字符串索引
let courseTitle = "Swift"
//获取字符串第一个字符的索引与值
let firstIndex = courseTitle.startIndex
let firstCharacter = courseTitle[firstIndex]
//获取字符串最后一个字符的索引与值
let endIndex = courseTitle.index(before: courseTitle.endIndex)
let endCharacter = courseTitle[endIndex]
//获取中间位置字符的索引与值
let middleIndex = courseTitle.index(courseTitle.startIndex, offsetBy: 2)
let middleCharacter = courseTitle[middleIndex]

//字符串的子串
let studentName = "luo liang"
let spaceIndex = studentName.index(of: " ")//xcode10.2中才有firstIndex(of:"")
let firstName = studentName[studentName.startIndex ..< spaceIndex!]
let firstName2 = studentName[..<spaceIndex!]
let surname = studentName[studentName.index(after: spaceIndex!)...studentName.index(before: studentName.endIndex)]
let bookInfo1 = "History book: world history"

//判断字符串是否含有前缀
if bookInfo1.hasPrefix("History book") {
    print("book1 is a history book.")
}
let bookInfo2 = "History book: China history"
//判断字符串时候含有后缀
if bookInfo2.hasSuffix("history") {
    print("book2 is a history book.")
}

//练习
var myHobbies = "Music Basketball Philosophy"
for char in myHobbies {
    print(char, terminator:" ")
}

print("\nThe number of characters in myHobbies is \(myHobbies.count)")
let str1 = "My hobbies", str2 = "is"
var info = str1 + str2 + myHobbies
print(info)
let space = " "
info = str1 + space + str2 + space + myHobbies
print(info)
print(info.uppercased())
print(info.lowercased())
var firstIndex = myHobbies.startIndex
let firstChar = myHobbies[firstIndex]
let lastIndex = myHobbies.index(before: myHobbies.endIndex)
let lastChar = myHobbies[lastIndex]
var middleIndex = myHobbies.index(firstIndex, offsetBy: 6)
var middleChar = myHobbies[middleIndex]
middleIndex = myHobbies.index(lastIndex, offsetBy: -20)
middleChar = myHobbies[middleIndex]
var spaceIndex = myHobbies.index(of: " ")!
let hobby1st = myHobbies[firstIndex..<spaceIndex]
firstIndex = myHobbies.index(after: spaceIndex)
let restOfMyHobbies = myHobbies[firstIndex...]
spaceIndex = restOfMyHobbies.index(of: " ")!
let hobby2nd = restOfMyHobbies[restOfMyHobbies.startIndex..<spaceIndex]
firstIndex = restOfMyHobbies.index(after: spaceIndex)
let hobby3rd = restOfMyHobbies[firstIndex...]
print("The first hobby is \(hobby1st)")
print("The second hobby is \(hobby2nd)")
print("The third hobby is \(hobby3rd)")

//compare hobby
if hobby1st == hobby2nd {
    print("The two hobbies are equal.")
}
if hobby1st.hasPrefix("musi") {
    print("The first hobby: \(hobby1st) has prefix: musi")
} else {
    print("The first hobby: \(hobby1st) hasn't prefix: musi")
}
if hobby2nd.hasSuffix("sophy") {
    print("The first hobby: \(hobby2nd) has suffix: sophy")
} else {
    print("The first hobby: \(hobby2nd) has suffix: sophy")
}