Swift2.0学习笔记(二)之switch语句与NSString

switch-case 语句

var rating="A"
switch rating{//该程序输出结果是:Great,case语句后不用加break
    case "A":   //case "a","A":
        print("Great")
    case "B":   //case "b","B":
        print("Just so-so")
    case "C":   //case "c","C":
        print("It's bad")
    default:    //在Swift中default语句不能去掉
        print("Error") //可用“()”做空语句,或者“break”
}
//如果想从一个case语句中跳到下一个case语句,可用关键字“fallthrough”
findAnswer: for m in 1...300{
    for n in 1...300{
        if m*m*m*m-n*n==15*m*n{
            print(m,n)
            break findAnswer
        }
    }
}
let point=(3,3)
switch point{
case let (x,y) where x == y:
    print("It's on the line x==y")
case let (x,y) where x == -y:
    print("It's on the line x==-y")
case let (x,y):
    print("It's just an ordinary point")
    print("The point is (\(x),\(y))")
}
let age = 18
if case 10...19 = age{
    print("You're a teenage.")
}
if case 10...19 = age , age >= 18{
    print("You're a teenage and in a college!")
}
let vector=(4,0)
if case ( let x, 0 ) = vector, x > 2 && x < 5{
    print("It's the vector!")
}
for case let i in 1...100 where i % 3 == 0{
    print(i)
}
func buy(money: Int , price: Int , capacity: Int , volume: Int){
    if money >= price{
        if capacity >= volume{
            print("I can buy it!")
            print("\(money-price) Yuan left")
            print("\(capacity-volume) cubic meters left")
        }else{
            print("No enough capacity")
        }
    }else{
        print("Not enough money")
    }
}

func buy2( money: Int , price: Int , capacity: Int , volume: Int){
    guard money >= price else{//保证money >= price 否则输出
        print("Not enough moeney")
        return
    }
    guard capacity >= volume else{//保证capacity >= volume
        print("Not enough capacity")
        return
    }
    print("I can buy it!")
    print("\(money-price) Yuan left.")
    print("\(capacity-volume) cubic meters left")
}
//定义字符(Charcter),使用双引号,但是要显式定义
var mark:Character = "!"

String和NSString的封装函数

var str = "Hello, Swift"
let startIndex = str.startIndex //startIndex==0
let spaceIndex =startIndex.advancedBy(6) //求出从startIndex开始位置6的字符
str[spaceIndex.predecessor()] //",",spaceIndex前一个字符
str[spaceIndex.successor()] //",",spaceIndex后一个字符
let s2 = NSString(format: "one third is %.2f", 1.0/3.0) //格式化输出小数
let s3: String = NSString(format: "one third ids %.2f", 1.0/3.0) as String //将NNString类型转换为String
let s6 = "   ---Hello --- " as NSString
s6.stringByTrimmingCharacterInSet(NSCharacterSet(charactersInString: " -")) //删除s6中的" "和"-"

猜你喜欢

转载自blog.csdn.net/m0_37281837/article/details/81901886
今日推荐