Swift 字符串+集合(三)

前端之家收集整理的这篇文章主要介绍了Swift 字符串+集合(三)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Strings and Characters 字符串和字符

String Literals 字符串字面量
用于为常量或变量提供初始值,可包含以下特殊字符
转义字符\0(空)、\\(反斜线)、\t(水平制表)、\n(换行)、\r(回车)、\"(双引号)、\'(单引号)
单字节Unicode , 写成\xnn,nn为两位十六进制数
双字节Unicode , 写成\unnnn,nnnn为四位十六进制数
四字节Unicode , 写成\Unnnnnnnn,nnnnnnnn为八位十六进制数


Initializing an Empty String 初始化空字符串
[objc] view plain copy
  1. varemptyString=""//emptystringliteral
  2. varanotherEmptyString=String()//initializerSyntax
  3. //thesetwostringsarebothempty,andareequivalenttoeachother
通过检查isEmpty属性判断是否为空
    ifemptyString.isEmpty{
  1. println("Nothingtoseehere")
  2. }
  3. //prints"Nothingtoseehere"

String Mutability 字符串的可变性
将字符串赋给变量来进行修改,或分配给常量来保证不被修改
    varvariableString="Horse"
  1. variableString+="andcarriage"
  2. //variableStringisnow"Horseandcarriage"
  3. letconstantString="Highlander"
  4. constantString+="andanotherHighlander"
  5. //thisreportsacompile-timeerror-aconstantstringcannotbemodified

Strings Are Value Types 值类型
Swift的String是值类型,如果创建了一个新的字符串,当进行常量、变量赋值或在函数方法中传递的时候都会进行值拷贝,In each case,a new copy of the existing String value is created,and the new copy is passed or assigned,not the original version.

Working with Characters 使用字符
String类型即Character字符的集合,每个字符代表一个Unicode字符,可用for-in循环来遍历字符串中的值
    forcharacterin"Dog!"{
  1. println(character)
  2. //D
  3. //o
  4. //g
  5. //!
或者,通过标明一个Character的类型并进行赋值,可声明一个独立的字符常量或变量
    letyenSign:Character="¥"

Counting Characters 计算字符数
调用全局的countElements函数计算字符串的字符数量,(有几个表情我省略了,想知道是什么看原文)
    letunusualMenagerie="Koala,Snail,Penguin,Dromedary"
  1. println("unusualMenageriehas\(countElements(unusualMenagerie))characters")
  2. //prints"unusualMenageriehas40characters"

Concatenating Strings and Characters 连接字符串和字符
    letstring1="hello"
  1. letstring2="there"
  2. letcharacter1:Character="!"
  3. letcharacter2:Character="?"
  4. letstringPlusCharacter=string1+character1//equals"hello!"
  5. letstringPlusString=string1+string2//equals"hellothere"
  6. letcharacterPlusString=character1+string1//equals"!hello"
  7. letcharacterPlusCharacter=character1+character2//equals"!?"
  8. varinstruction="lookover"
  9. instruction+=string2
  10. //instructionnowequals"lookoverthere"
  11. varwelcome="goodmorning"
  12. welcome+=character1
  13. //welcomenowequals"goodmorning!"

String Interpolation 插值
写在括号中的表达式不能包含非转义双引号("")和反斜杠(\),回车和换行符
    letmultiplier=3
  1. letmessage="\(multiplier)times2.5is\(Double(multiplier)*2.5)"
  2. //messageis"3times2.5is7.5"

Comparing Strings 字符串比较
String Equality 字符串相等,两个字符串完全相等,两者才相等
    letquotation="We'realotalike,youandI."
  1. letsameQuotation="We'realotalike,youandI."
  2. ifquotation==sameQuotation{
  3. println("Thesetwostringsareconsideredequal")
  4. //prints"Thesetwostringsareconsideredequal"
Prefix and Suffix Equality 前缀/后缀相等
    letromeoAndJuliet=[
  1. "Act1Scene1:Verona,Apublicplace",
  2. "Act1Scene2:Capulet'smansion",
  3. "Act1Scene3:AroominCapulet'smansion",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "Act1Scene4:AstreetoutsideCapulet'smansion",248)"> "Act1Scene5:TheGreatHallinCapulet'smansion",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "Act2Scene1:OutsideCapulet'smansion",248)"> "Act2Scene2:Capulet'sorchard",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "Act2Scene3:OutsideFriarLawrence'scell",248)"> "Act2Scene4:AstreetinVerona",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> "Act2Scene5:Capulet'smansion",248)"> "Act2Scene6:FriarLawrence'scell"
  4. ]
  5. varact1SceneCount=0
  6. forsceneinromeoAndJuliet{
  7. ifscene.hasPrefix("Act1"){
  8. ++act1SceneCount
  9. }
  10. println("Thereare\(act1SceneCount)scenesinAct1")
  11. //prints"Thereare5scenesinAct1"
  12. varmansionCount=0
  13. varcellCount=0
  14. ifscene.hasSuffix("Capulet'smansion"){
  15. ++mansionCount
  16. }elseifscene.hasSuffix("FriarLawrence'scell"){
  17. ++cellCount
  18. println("\(mansionCount)mansionscenes;\(cellCount)cellscenes")
  19. //prints"6mansionscenes;2cellscenes"

Uppercase and Lowercase Strings 大写和小写
    letnormal="Couldyouhelpme,please?"
  1. letshouty=normal.uppercaseString
  2. //shoutyisequalto"COULDYOUHELPME,PLEASE?"
  3. letwhispered=normal.lowercaseString
  4. //whisperedisequalto"couldyouhelpme,please?"




Collection Type 集合类型

Swift提供数组和字典两种集合类型来存储数据,数组按顺序存储,字典按键值对存储

Arrays 数组

创建数组
由一系列逗号分隔并由方括号包含,以下定义一个字符串类型数组,为String[],由于Swift会自动判断所定义的变量的类型,所以String[] 也可以省略
    varshoppingList:String[]=["Eggs","Milk"]
  1. //shoppingListhasbeeninitializedwithtwoinitialitems
  2. //varshoppingList=["Eggs","Milk"]
  3. varsomeInts=Int[]()
  4. println("someIntsisoftypeInt[]with\(someInts.count)items.")
  5. //prints"someIntsisoftypeInt[]with0items."
  6. varthreeDoubles=Double[](count:3,repeatedValue:0.0)
  7. //threeDoublesisoftypeDouble[],andequals[0.0,0.0,0.0]
  8. varanotherThreeDoubles=Array(count:3,0); background-color:inherit">repeatedValue:2.5)
  9. //anotherThreeDoublesisinferredasDouble[],andequals[2.5,2.5,2.5]

访问和修改数组的值
可通过数组的方法属性,或者下标来使用数组,等等等等,以下代码推荐使用在Xcode6下看一遍,加深体会
    println("Theshoppinglistcontains\(shoppingList.count)items.")
  1. //prints"Theshoppinglistcontains2items."
  2. ifshoppingList.isEmpty{
  3. println("Theshoppinglistisempty.")
  4. }else{
  5. println("Theshoppinglistisnotempty.")
  6. //prints"Theshoppinglistisnotempty."
  7. shoppingList.append("Flour")
  8. //shoppingListnowcontains3items,andsomeoneismakingpancakes
  9. shoppingList+="BakingPowder"
  10. //shoppingListnowcontains4items
  11. shoppingList+=["ChocolateSpread","Cheese","Butter"]
  12. //shoppingListnowcontains7items
  13. varfirstItem=shoppingList[0]
  14. //firstItemisequalto"Eggs"
  15. shoppingList[0]="Sixeggs"
  16. //thefirstiteminthelistisnowequalto"Sixeggs"ratherthan"Eggs"
  17. shoppingList[4...6]=["Bananas","Apples"]
  18. //shoppingListnowcontains6items
  19. shoppingList.insert("MapleSyrup",0); background-color:inherit">atIndex:0)
  20. //"MapleSyrup"isnowthefirstiteminthelist
  21. letmapleSyrup=shoppingList.removeAtIndex(0)
  22. //theitemthatwasatindex0hasjustbeenremoved
  23. //shoppingListnowcontains6items,andnoMapleSyrup
  24. //themapleSyrupconstantisnowequaltotheremoved"MapleSyrup"string
  25. firstItem=shoppingList[0]
  26. //firstItemisnowequalto"Sixeggs"
  27. letapples=shoppingList.removeLast()
  28. //thelastiteminthearrayhasjustbeenremoved
  29. //shoppingListnowcontains5items,andnocheese
  30. //theapplesconstantisnowequaltotheremoved"Apples"string
  31. varsixDoubles=threeDoubles+anotherThreeDoubles
  32. //sixDoublesisinferredasDouble[],2.5]

遍历数组
    foriteminshoppingList{
  1. println(item)
  2. //Sixeggs
  3. //Milk
  4. //Flour
  5. //BakingPowder
  6. //Bananas
或者使用全局enumerate函数来对数组进行遍历,enumerate返回一个索引和一个数据值
    for(index,value)inenumerate(shoppingList){
  1. println("Item\(index+1):\(value)")
  2. //Item1:Sixeggs
  3. //Item2:Milk
  4. //Item3:Flour
  5. //Item4:BakingPowder
  6. //Item5:Bananas

字典

字典中的数据是无须的,通过键来取数据,不同于OC中的NSDictionary 和 NSMutableDictionary可以用任意类型的对象来做键和值,Swift中必须提前声明

定义字典,airport定义为Dictionary<String,String>,意味着字典的键和值都是String类型的
    airports:Dictionary<String,String>=["TYO":"Tokyo","DUB":"Dublin"]
  1. //varairports=["TYO":"Tokyo","DUB":"Dublin"]
  2. varnamesOfIntegers=Dictionary<Int,String>()
  3. //namesOfIntegersisanemptyDictionary<Int,String>

对字典进行操作
通过字典的方法属性和下标进行操作
    println("Thedictionaryofairportscontains\(airports.count)items.")
  1. //prints"Thedictionaryofairportscontains2items."
  2. airports["LHR"]="London"
  3. //theairportsdictionarynowcontains3items
  4. airports["LHR"]="LondonHeathrow"
  5. //thevaluefor"LHR"hasbeenchangedto"LondonHeathrow"
  6. ifletoldValue=airports.updateValue("DublinInternational",0); background-color:inherit">forKey:"DUB"){
  7. println("TheoldvalueforDUBwas\(oldValue).")
  8. //prints"TheoldvalueforDUBwasDublin."
  9. ifletairportName=airports["DUB"]{
  10. println("Thenameoftheairportis\(airportName).")
  11. else{
  12. println("Thatairportisnotintheairportsdictionary.")
  13. //prints"ThenameoftheairportisDublinInternational."
  14. airports["APL"]="AppleInternational"
  15. //"AppleInternational"isnottherealairportforAPL,sodeleteit
  16. airports["APL"]=nil
  17. //APLhasnowbeenremovedfromthedictionary
  18. ifletremovedValue=airports.removeValueForKey("DUB"){
  19. println("Theremovedairport'snameis\(removedValue).")
  20. println("TheairportsdictionarydoesnotcontainavalueforDUB.")
  21. //prints"Theremovedairport'snameisDublinInternational."


字典的遍历

    for(airportCode,airportName)inairports{
  1. println("\(airportCode):\(airportName)")
  2. //TYO:Tokyo
  3. //LHR:LondonHeathrow
  4. forairportCodeinairports.keys{
  5. println("Airportcode:\(airportCode)")
  6. //Airportcode:TYO
  7. //Airportcode:LHR
  8. forairportNameinairports.values{
  9. println("Airportname:\(airportName)")
  10. //Airportname:Tokyo
  11. //Airportname:LondonHeathrow
  12. letairportCodes=Array(airports.keys)
  13. //airportCodesis["TYO","LHR"]
  14. letairportNames=Array(airports.values)
  15. //airportNamesis["Tokyo","LondonHeathrow"]

猜你在找的Swift相关文章