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"//"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}"//"💖"
let eAcute:Character = "\u{e9}" //"é" 一个标量
let combinedEAcute:Character = "\u{65}\u{301}"//"é"两个标量
let precomposed:Character = "\u{D55C}" //预先构成
let decomposed:Character = "\u{1112}\u{1161}\u{11AB}" //分解"한"// ᄒ, ᅡ, ᆫ
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 = "!"//!
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"//"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"]
swift:基本数据类型
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1.常量:使用let声明 2.变量:使用var声明 3.整型 4.浮点型 5.布尔型:Bool 6.字符串 7.字...