swift:基本數據類型


import UIKit

var str = "202111122"
//1.字符串操作
var ns1=(str as NSString).substringFromIndex(5)

//2.變量賦值
 var myVarible = 50.3
myVarible = 34

//3.常量
let  myConstant = 45
// myConstant = 23  (X):myConstant不可以再被賦值,因為他是常量

//4. implicit模糊的類型:由編譯器自己根據等號右邊的值 推導implicitInterger 為什么類型
let implicitInterger = 70
let implicitDouble = 70.04

//5. explicit明確的類型:當等號右邊的值沒有初始值,或者計算機沒有足夠的信息來推導他的類型,必須在變量后面指定他的類型  通過:隔開
let explicitDouble:String =  "2.093"
let explicitValue:Double = 4


//5.類型轉換  值不會隱性轉換為另一種類型,如果需要轉換值為不同的類型,必須指明他要轉的類型
let label = "this width is  : "
let width = 89
let widthLabrl = label + String(width)
//let widthLabel = label + (width)不同類型的值拼接 會報錯:Binary operator '+' cannot applied to operands od type 'Sting' and 'Int'


//6.有更簡單的方法轉字符串類型 \() 
let apples = 3
let peaches = 4
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + peaches) pieces of fruit."


let height = 1.68
let myHeight = "I am \(height) cm."


//7.數組與字典 
var shoppingList = ["catfish","water","tulips","tulips","blue paint"]
shoppingList[1]  = "bottle os water"

var occupations = ["Malcolm":"Captain",
"Keylee":"Mechanic",]

occupations["Jayne"] = "Public Relation"

//8. 初始化字典與數組
let emptyArray = [String]()
//let empty1Array = String[]()  已經過期
let emptyDictionary = Dictionary<String, Float>()

//basic operators
//1. range  //半閉合的范圍range ..<    //全閉合的范圍range ...
3..<5 // 代表一個范圍3到5  3..<5 //半閉合的范圍range
3...5 // 代表三到6  3..<6  //全閉合的范圍range
print("\(3...5)")  //"3..<6\n"

for index in 1...5{
print("\(index) times 5 is \(index *  5)")
    // 1 times 5 is 5
    // 2 times 5 is 10
    // 3 times 5 is 15
    // 4 times 5 is 20
    // 5 times 5 is 25
}

for index in 1..<5{

print("\(index) times is \(index * 5)")
    // 1 times 5 is 5
    // 2 times 5 is 10
    // 3 times 5 is 15
    // 4 times 5 is 20
}

let names = ["Ann","Alex","Brian","Jack","Cjoe"]
let count = names.count  //5
for i in 0..<count{
print("preson \(i + 1) is called \(names[i])")
    // Person 1 is called Anna
    // Person 2 is called Alex
    // Person 3 is called Brian
    // Person 4 is called Jack
    //person 5 is called Cjoe

}

let decimalInteger = 17
let binaryInteger = 0b10001       // 17 in binary notation
let octalInteger = 0o21           // 17 in octal notation
let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

let decimalDouble = 12.1875
let exponentDouble = 1.21875e1 //12.1875
let hexadecimalDouble = 0xC.3p0// 12.1875

let π = 3.14159 //3.14159
let 你好 = "你好世界"  //3.14159
let ???? = "dogcow"  //"dogcow"

let paddedDouble = 000123.456  //123.456
let oneMillion = 1_000_000  //1000000
let justOverOneMillion = 1_000_000.000_000_1 //1000000




//2. terminology 術語    ternary三元的
-1//unary一元的
2 + 3 //binary二元的
true ? 4 : 1 // ternary三元的

let(x, y) = (1, 2)
x//1
y//2

//(1, "zebra") < (2, "apple")   // true because 1 is less than 2
//(3, "apple") < (3, "bird")    // true because 3 is equal to 3, and "apple" is less than "bird"
//(4, "dog") == (4, "dog")      // true because 4 is equal to 4, and "dog" is equal to "dog"

//Nil Coalescing Operator  (a??b == a != nil ? a! : b)

let defautColorName = "red"
var userDefinedColotName:String?
var colorNameToUse = userDefinedColotName ?? defautColorName  //red

var userDefinedColotName1 = "green"
var colorNameToUse1 = userDefinedColotName1 ?? defautColorName  //green

//1.typealias  取別名
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min  //0

//2.Boolean
let turnipsAreDelicious = false
let carrotIsCarrot = true

if turnipsAreDelicious{
print("Mmm. tasty turnips (tenip大頭菜胡蘿卜).")
}else{
print("Eww,turnips are horrible")//"Eww,turnips are horrible\n"
}


//3.元組 tuples:把多個值組合成一個復合值。元組內的值可以使任意類型,并不要求是相同類型。
let http404Eror = (404,"Not Found") //(.0 404, .1 "Not Found")

let (statusCode, statusMessage) = http404Eror//你可以將一個元組的內容分解(decompose)成單獨的常量和變量,然后你就可以正常使用它們了
print("the status code is  \(statusCode)") //"the status code is  404\n"
print("the statusMessage is \(statusMessage)")  //the statusMessage is Not Found

let (justTheStatusCode, _) = http404Eror //如果你只需要一部分元組值,分解的時候可以把要忽略的部分用下劃線(_)標記
    print("I just want the status code \(justTheStatusCode)")//"I just want the status code 404\n"

print(" access the subscipt to get that value \(http404Eror.0)")//" access the subscipt to get that value 404\n"
print("通過下標來獲取值 \(http404Eror.1)")//"通過下標來獲取值 Not Found\n"

let http200Status = (statusCode:200, description:"OK") //定義元組的時候給單個元素命名通過名字來獲取這些元素的值
print("the status code is \(http200Status.statusCode)")//"the status code is 200\n"

//注意:元組在臨時組織值的時候很有用,但是并不適合創建復雜的數據結構。如果你的數據結構并不是臨時使用,請使用類或者結構體而不是元組。請參考類和結構體。

//1.字符串
var emptyStr = "1"
var emptyStr1 = String()
emptyStr += "zalal" + "layeye"http://"1zalallayeye"

//2 轉義字符
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
//3 特殊字符
let dollarSign = "\u{24}" //"$"
let blackHeat = "\u{2665}" //"?"
let sparklingHeart = "\u{1F496}"http://"??"

let eAcute:Character = "\u{e9}" //"é" 一個標量
let combinedEAcute:Character = "\u{65}\u{301}"http://"é"兩個標量

let precomposed:Character = "\u{D55C}" //預先構成
let decomposed:Character = "\u{1112}\u{1161}\u{11AB}" //分解"?"http:// ?, ?, ?

let enclosedEAcute:Character = "\u{E9}\u{20DD}" //"é?"
let regionalIndicatorForUS = "\u{1F1FA}\u{1F1F8}" //"????"
var word = "cafe"
print("the number of character in \(word) is \(word.characters.count)")//"the number of character in cafe is 4\n

//4 大小寫轉換
let uppercase = wiseWords.uppercaseString //""IMAGINATION IS MORE IMPORTANT THA
let lowercase = uppercase.lowercaseString//""imagination is more important than knowledge" - einstein"

//5 Unicode
let dogString = "Dog??" //"Dog??"
for character in dogString.characters{
print("character")  //(4 times)
}
for codeUnit in dogString.utf8 {
    print("\(codeUnit) ") //7 times
}
for codeUnit in dogString.utf16 {
    print("\(codeUnit) ", terminator: "")//5times
}

for scalar in dogString.unicodeScalars {
    print("\(scalar.value) ", terminator: "")//4times
}


let exclamationMark:Character = "!"http://!
let catCharacters:[Character] = ["C","a","t","??"]//["C", "a", "t", "??"]
let catString = String(catCharacters)  //"Cat??"


//6 字符串的索引String indice
let greeting = "Guten Tag!"
greeting[greeting.startIndex]  //"G"
greeting[greeting.endIndex.predecessor()]  //!  前生 前輩
greeting[greeting.startIndex.successor()]//u 后輩
let index = greeting.startIndex.advancedBy(2)
greeting[index] //"t"
greeting.endIndex //10 因為字符串以\n結尾 所以index最大值為10 了
greeting.endIndex.predecessor()//9
greeting.startIndex.successor()//1
greeting.startIndex //0
//greeting[greeting.endIndex]  超過了字符串的范圍 會報錯
//greeting.endIndex.successor() // error

for index in greeting.characters.indices{
    print("\(greeting[index])", terminator:"")//(10 times)
}

//7. 對字符串進行insert 以及remove
var welcome = "hello"
welcome.insert("!", atIndex: welcome.endIndex) //"hello!"
welcome.insertContentsOf(" there".characters, at: welcome.endIndex.predecessor())

welcome.removeAtIndex(welcome.endIndex.predecessor()) //"!"
let range  = welcome.endIndex.advancedBy(-6)..<welcome.endIndex//5..<11
welcome.removeRange(range)//5..<11

let  eAcuteQuestion = "Voulez-vous un caf\u{E9}" //"Voulez-vous un café"

let latinCapitalLetterA: Character = "\u{41}"  //"A"
let cyrillicCapitalLetterA: Character = "\u{0410}"  //"A"
if latinCapitalLetterA != cyrillicCapitalLetterA {
    print("These two characters are not equivalent")  //"These two characters are not equivalent\n"
}

//MARK:  collection types -----------------

//1. 數組 Array
var someInt = [Int]()//[]
someInt.append(3) //[3]
var someInt1 = [Int](count:3, repeatedValue:2)  //[2, 2, 2]

var threeDouble = [Double](count:3,repeatedValue:2.03)//[2.03, 2.03, 2.03]
var  anotherThreeDoubles = [Double](count:3, repeatedValue:2.5)//[2.5, 2.5, 2.5]
var sixDouble = threeDouble + anotherThreeDoubles //[2.03, 2.03, 2.03, 2.5, 2.5, 2.5]

var shoppingList:[String] = ["eggs","milk"] //["eggs", "milk"]
var shoppinglist = [String](count:3, repeatedValue:"milk")   //["milk", "milk", "milk"]

if shoppingList.isEmpty{
print("this empty shoppinglist")
}else{
print("this shoppinglist is not empty") //"this shoppinglist is not empty\n"
}

shoppingList.append("flour")//["eggs", "milk", "flour"]
shoppingList += ["Baking powder"]
shoppingList += ["chocolate spread","cheese","butter"]
shoppingList[0]//"eggs"
shoppingList[0] = "banana"http://"banana"
shoppingList[4...6] //["chocolate spread", "cheese", "butter"]
shoppingList.count//7
shoppingList[4...6] = ["apples","peaches"]//["apples", "peaches"]
shoppingList//["banana", "milk", "flour", "Baking powder", "apples", "peaches"]
shoppingList.count//6

shoppingList.insert("Maple syrup", atIndex: 1)//["banana", "Maple syrup", "milk", "flour", "Baking powder", "apples", "peaches"]
let mapleSyrup = shoppingList.removeAtIndex(1)  //"Maple syrup"
shoppingList//["banana", "milk", "flour", "Baking powder", "apples", "peaches"]

let peaches = shoppingList.removeLast()

for item in shoppingList{
print("\(item)")
}

//enumerate產生一個元組(index,value)
for(index, value) in shoppingList.enumerate(){
    print("item \(index + 1): \(value)")
    //items5 apples
}



//2. Set 集合  無序的 只能用來存儲一種類型
var letters = Set<Character>()//[]

letters.insert("a")  //{"a"}
letters = []//[]

var favoriteGenres:Set<String> = ["Rock","Classical","Hip hop"]//{"Rock", "Classical", "Hip hop"}

var favoriteGenres1:Set = ["Rock","Classical","Hip hop"]//集合全部是一個類型,swift可以自己推斷set是String類型的
favoriteGenres.insert("Jazz")  //{"Rock", "Classical", "Jazz", "Hip hop"}

//刪除集合里面的某個元素
if let removeGenre = favoriteGenres.remove("Rock")
{
    print("\(removeGenre)? I'm over it"); //"Rock? I'm over it\n"
}else{
print("I never much cared for that")

}
//判斷集合是否包含某個元素
if favoriteGenres.contains("Funk"){
print("I  get up on the good foot")
}else{
print("It's to funky in here")
}

//遍歷
for genre in  favoriteGenres{
print("\(genre)")
    // Classical
    // Jazz
    // Hip hop
}

//排序  按照從長到短的順序排列
for genre in favoriteGenres.sort(){
    print("\(genre)")

}


//集合的運算
let oddDidgist: Set = [1, 3, 5,7,9]
let evenDigist : Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers:Set = [2, 3, 5,7]

oddDidgist.union(evenDigist).sort() //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  //從小到大的順序  union 合
oddDidgist.intersect(evenDigist).sort()//[]  intersect 交
oddDidgist.subtract(singleDigitPrimeNumbers).sort()// [1, 9] subtract減去相同的元素
oddDidgist.exclusiveOr(singleDigitPrimeNumbers).sort()//[1, 2, 9]   exlusiceOr(1- intersect)

let houseAnimals: Set = ["??","??"]
let familyAnimals:Set = ["??","??","??","??","??","??"]
let cityAnimals:Set = ["??","??"]
houseAnimals.isSubsetOf(familyAnimals) // true  hourseAnimals 是familyAnimals的子集
familyAnimals.isSupersetOf(houseAnimals)//true  familyAnimals 是 hourseAnimal 的父集
familyAnimals.isDisjointWith(cityAnimals)//true  familyAnimals 不包含cityAnimals


//3. Dictionary

var nameOfIntegers = [Int:String]()

nameOfIntegers[16] = "sixteen"
nameOfIntegers//[16: "sixteen"]
nameOfIntegers = [:]//[:]

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports1 = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London Heathrow"


//更新字典的key值  updateValue
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB"){

}
airports  //["DUB": "Dublin Airport", "LHR": "London Heath


//remove key  把value 設置為nil
airports["APL"] = "APPLE INTERNATIONAL"
airports//["APL": "APPLE INTERNATIONAL", "YYZ": "Toron
airports["APL"] = nil
airports//"YYZ": "Toronto Pearson", "DUB": "Dublin Airpo


if let removedValue = airports.removeValueForKey("DUB")
{
airports//["YYZ": "Toronto Pearson", "LHR": "London Hea
    removedValue//"Dublin Airport"

}

for (airportCode, airportName) in airports { //返回的是元組(key,value)
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow


for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR

for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow


let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]

let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]





最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容