Swift基礎語法2

//區間運算符.....<

for   icount in1...5{

    print(icount)

}

for   icount in1..<5{

    print(icount)

}


//字符串範圍也可以使用區間運算符

//字符串截取

let words = "baidu.com"


//不使用區間運算符

let index = words.startIndex.advancedBy(2)

let index2 = words.startIndex.advancedBy(4)

let range1 = Range<String.Index>(start:index, end: index2)

let rangeStr1 = words.substringWithRange(range1)//ge

print(rangeStr1)


//使用區間運算符

let range2 = words.startIndex.advancedBy(2)..<words.startIndex.advancedBy(4)

let rangeStr2 = words.substringWithRange(range2)//ge

print(rangeStr2)


//,區間運算符除了返回一個Range外,還可以接受Comparable的輸入,返回ClosedIntervalHalfOpenInterval

let wordsCart = "Baidu.com"


let interval = "a"..."z"

for c inwordsCart.characters {

    if !interval.contains(String(c)){//contains比較包含關係

        print("\(c)不是小寫字母")

    }

}


// 賦值運算

//**************  Swift 的賦值運算符沒有返回值 **************

let (x,y,z) = (2,3,4)

print(x)

print(z)

if x==y{//此處用=將會報錯

    print("---->1")

}else

{

    print("---->2")

}

//溢出運算你往一個整型常量或變量賦於一個它不能承載的大數 Swift不同意這樣做

// 如果需要溢出運算的話 swift提供了溢出運算符 &+ &- &* &/


let lestString = "hello"

let rightString = "word"

print(lestString+rightString)//swift提供了字符串直接相加減


print(9%5)


//浮點數取餘運算依然是浮點數

print(8.5%3)


//oc一樣的是 

/* ++前置的時候,先自増再返回。

  ++後置的時候,先返回再自增。*/

print(9>8 ?1 : 0)//三元運算符


//字符串

/*Swift語言的String類型卻是一種快速、現代化的字符串實現。每一個字符串都是由獨

 立編碼的Unicode字符組成,並提供了用於訪問這些字符在不同 Unicode表示的支持*/

//SwiftString類型已經和Foundation NSString類進行了無縫橋接

//swift  自動推斷對象的類型


/*1.特殊的轉義字符  \0 (空字符)\\(反斜線)\t (水平製表符)\n (換行符)\r (回車符)\" (雙引號)\' (單引號)

 2.單字節  Unicode標量,寫成  \xnn,其中  nn爲兩位十六進制數。

 3.雙字節  Unicode標量,寫成  \unnnn,其中  nnnn爲四位十六進制數。

 4.四字節  Unicode標量,寫成  \Unnnnnnnn,其中  nnnnnnnn爲八位十六進制數。*/


print("1234\n4321")

print("12\0\\34\r4'3'21")


//進制轉化

print(String(13,radix:2))

print(String(13,radix:8))

print(String(13,radix:16))


var emptyString = ""

var anotherEmptyString = String()

print("\(emptyString) and\(anotherEmptyString)")

if emptyString.isEmpty//監測是否爲空

{

    print("empty")

} else

{

    print("NO Empty")

}


var variableString ="Horse" //此處如果用let的話將不能進行加

variableString += " and carriage"

print(variableString)


//字符串的長度


let unusualMenagerie ="abcdefjhigklmnopqrstuvwxyz!@#@#@#@#@"

let characterCount = unusualMenagerie.characters.count


print("nunsualMessageeie has\(characterCount) characters")


//字符串的插入

let multiplier = 3

let message = "\(multiplier) times 2.5 is\(Double(multiplier) *2.5)"


//字符串比較  swift分爲前綴相等和後綴相等和全等

// 全等就是==

// 前綴相等


let remeoAllData = [

    "A Cat has two ears",

    "A Cat has two ears",

    "A Cat has two ears",

    "Two Cat has two ears",

    "A Cat has two ears",

    "A Cat has one ears",

    "A Cat has two ears",

    "Two Cat has four ears",


]

var earsCount = 0

for scene inremeoAllData

{

    if scene.hasPrefix("A Cat")

    {

        earsCount +=1

    }


}

print(earsCount)


for scene inremeoAllData

{

    if scene.hasSuffix("two ears")

    {

        earsCount +=1

    }

    

}

print(earsCount)

//轉換成大小寫

let  upperAndLower ="You are a small pag"

print(upperAndLower.uppercaseString)

print(upperAndLower.lowercaseString)


let dogString = "dogString"


for codeUnit indogString.utf8{

    print(codeUnit)

}

for codeUnit in dogString.unicodeScalars{

    print(codeUnit)

}

for codeUnit indogString.utf16 {

    print(codeUnit)

}


// 數組和字典

/*Swift 如果創建一個 Int類型的數組,就不能向其中加入不是Int類型的任何數據

  oc中只要創建一個數組類型可以裝任何類型的元素, swift相比而言更加安全*/


//創建數組


var shopingList = ["2","1"]

print(shopingList.count)

print(shopingList[1])

//追加元素

shopingList.append("34")

print(shopingList)

//替換

shopingList[1...2]=["a","v"]

print(shopingList)

//固定的位置插入一頭豬

shopingList.insert("pig", atIndex:0)

print(shopingList)

//再將這頭豬刪除

shopingList.removeAtIndex(0)

print(shopingList)

shopingList.removeLast()

print(shopingList)


shopingList.insert("flash", atIndex:2)

// 遍歷數組加下標

for (index , value) inshopingList[0..<shopingList.count].enumerate()

{

    print("Item \(index+1) :\(value)")

}


let someArray: Array<String> = ["Alex","Brian", "ddd"]

var someInts: NSMutableArray = []


var shopingDoc = [

    "one":"1",

    "two":"2",

    "three":"3",

]

shopingDoc.updateValue("dog", forKey:"two")

//遍歷字典的元素

print(shopingDoc)

for(airportCode,airportName) in shopingDoc {

    print("\(airportCode) :\(airportName)")

}

//遍歷字典的value

for airportCode inshopingDoc.keys

{

    print(airportCode)

}

for airportCode inshopingDoc.values

{

    print(airportCode)

}


let airportCodes = Array(shopingDoc.keys)

let airportNames = Array(shopingDoc.values)

print("\(airportCodes)------>\(airportNames)")


var namesOfIntegers = Dictionary<Int,String>()

print(namesOfIntegers)

namesOfIntegers[12]="12?"

namesOfIntegers=[:]

print(namesOfIntegers)


for index in0 ..< 3 {

    print("index is\(index)")

}

let someCharacter: Character ="e"


//不用寫bleak默認直接有的


switch someCharacter {

case "a""i", "o","u":

    print("\(someCharacter) is a vowel")

case "b","c", "d","f", "g","h", "j","k", "l","m",

     "n","p", "q","r", "s","t", "v","w", "x","y", "z","e":

    print("\(someCharacter) is a consonant")

default:

    print("\(someCharacter) is not a vowel or a consonant")

}


let count = 3_000_000_000_000

let countedThings ="stars in the Milky Way"

var naturalCount: String

switch count {

case 0:

    naturalCount ="no"

case 1...3:

    naturalCount ="a few"

case 4...9:

    naturalCount ="several"

case 10...99:

    naturalCount ="tens of"

case 100...999:

    naturalCount ="hundreds of"

case 1000...999_999:

    naturalCount ="thousands of"

default:

    naturalCount ="millions and millions of"

}

print("There are\(naturalCount)\(countedThings).")


// Swift 可以使用語句中可以使用元組測試多個值

//判斷實在x軸還是y軸還是那個位置

let somePoint = (1,0)

switch somePoint {

case (0,0):

    print("(0, 0) is at the origin")

case (_,0):

    print("(\(somePoint.0), 0) is on the x-axis")

case (0,_):

    print("(0,\(somePoint.1)) is on the y-axis")

case (-2...2, -2...2):

    print("(\(somePoint.0),\(somePoint.1)) is inside the box")

default:

    print("(\(somePoint.0),\(somePoint.1)) is outside of the box")

}


//值綁定(value binding):case分支允許將要匹配的值綁定給臨時常量或變量,這些常量或變量在該 case分支可以被引用。

let anotherPoint = (2,0)

switch anotherPoint {

case (let x,0):

    print("on the x-axis with an x value of\(x)")

case (0,let y):

    print("on the y-axis with a y value of\(y)")

case let (x, y):

    print("somewhere else at (\(x),\(y))")

}


//case 分支模式可以使用 where語句判斷額外的條件

let yetAnotherPoint = (1, -1)

switch yetAnotherPoint {

case let (x, y)where x == y:

    print("(\(x),\(y)) is on the line x == y")

case let (x, y)where x == -y:

    print("(\(x),\(y)) is on the line x == -y")

case let (x, y):

    print("(\(x),\(y)) is just some arbitrary point")

}

//控制轉移語句

/*

 continue 讓循環體立刻停止本次循環,重新開始下一次循環

 break 立刻結束(跳出)整個控制流的執行

 fallthrough

 return

 */

//Fallthrough 達到貫穿效果這個關鍵字可以達到c語言和oc中的switch循環語句不用每次循環都結束

//標籤聲明

//標籤語言


//函數 -----用來完成特定任務的功能獨立的代碼塊------

func sayHello(personName: String) -> String {

    let greeting ="Hello, " + personName +"! "

    return greeting

}

print(sayHello("王爺"))


func aginSayHello(helloOne:String,helloTwo:Int) ->String {

    return"hello," + helloOne + "今年\(helloTwo)歲了"

    

}

print(aginSayHello("王爺", helloTwo: 25))


//兩數相減

func halfOpenRangeLength(start:Int, end: Int) ->Int {

    return end - start

}

print(halfOpenRangeLength(1, end:3))


//

func arithmeticMean(numbers: Double...) -> Double {

    var total:Double = 0

    for numberin numbers {

        total += number

    }

    return total /Double(numbers.count)

}

arithmeticMean(1,2, 3,4, 5,6,7,8)


func printlnAllValue(val : Int){

    for aain 0...100 {

        for bbin 0...100 {

            if aa * bb == val {

                 print (aa , bb)

            }

        }

    }

    

}

print(printlnAllValue(30))

//多個返回值

func backCount(string: String) -> (vowels:Int, consonants: Int, others: Int) {

    var vowels =0, consonants = 0, others =0

    for characterin string.characters {

        switchString(character).lowercaseString {

        case"a", "e","i", "o","u":

            vowels += 1

        case"b", "c","d", "f","g", "h","j", "k","l", "m",

             "n","p", "q","r", "s","t", "v","w", "x","y", "z":

            consonants += 1

        default:

            others += 1

        }

    }

    return (vowels, consonants, others)

}

print("返回值\(backCount("some arbitrary string! ").consonants)")

print("返回值\(backCount("some arbitrary string! ").vowels)")

print("返回值\(backCount("some arbitrary string! ").others)")



func join(s1: String, s2:String, joiner: String) -> String {

    return s1 + joiner + s2

}

print(join("nihao", s2:"--wangye", joiner: "----dage"))


//交換

func swapTwoInts(inout a:Int, inout b:Int) {

    let temporaryA = a

    a = b

    b = temporaryA

}

var someInt = 3

var anotherInt = 107

swapTwoInts(&someInt, b: &anotherInt)

print("someInt is now\(someInt), and anotherInt is now\(anotherInt)")



struct FixedLengthRange {

    var firstValue:Int

    let length:Int

}

var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)

print(rangeOfThreeItems.firstValue)


Demo下載:http://download.csdn.net/detail/bddzzw/9629700


發佈了73 篇原創文章 · 獲贊 4 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章