//区间运算符...和..<
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的输入,返回ClosedInterval或HalfOpenInterval
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表示的支持*/
//Swift的String类型已经和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.youkuaiyun.com/detail/bddzzw/9629700