Swift中switch与OC中的比较

1. Swift语法中 switch与 OC 中的比较

1> 在OC中的switch
  • 必须是整数(int)类型,他只能判断整数
  • 可以穿透,可以连着写两个case条件语句但是不加break
  • 必须要带上break,表示跳出条件语句
  • 在case中定义变量要加大括号,保证分隔作用域
  • 可以不写default
  • default位置可以随便放
2> 在Swift中的switch
  • 不需要break,只要符合其中一个case的条件语句,就会跳出swich
  • 不局限在对 int 分支,可以对任意数据类型进行检测(它的可以是对象,也可以duoble类型)
  • 不能没有default,default位置只能在最后
  • 各个cese之间不能穿透,如果有多个值,可以使用","隔开
  • 定义变量不需要使用{}分隔作用域
  • 在Swift中,必须涵盖所有条件,每个case至少包含一条语句
3> Swift的swich相比于OC更加的强大

它还可以使用在别的上面

  • 可以使用区间运算
  • 可以用在元组里面
  • 值绑定(swich的case可以将匹配到的值绑定为一个临时的常量或者变量,来给case函数体使用)
  • 可以使用where分句来检查是否符合特定的约束(根据条件绑定)
  • 复合匹配
  • 复合值绑定
  • fallthrough:如果需要C或者OC一样风格的贯穿行为,可以使用fallthrogh,只要使用了fallthrogh,不会立即跳出switch语句,后面的case条件语句一样会执行
  • 语句标签:可以用语句标签来给循环语句或者条件语句做标记.

2.两者区别代码说明

  • OC代码
int score = 10;
        switch (score) {
            case 10:
                NSLog(@"优");
                break;
            case 9:
                NSLog(@"良");
                break;
            case 8:
                NSLog(@"一般");
                break;
            default:
                NSLog(@"差");
                break;
        }
        //输出结果:优
//可以穿透
        int score = 10;  //这个变量只能是整数,不能判断对象等
        switch (score) {
            case 10:
            case 9:  //oc中的switch可以穿透,可以连着写两个case条件但是中间不加break
                NSLog(@"优良");
                break;    //必须要带上break,表示跳出条件语句
            case 8:
                NSLog(@"一般");
                break;
            default:
                NSLog(@"差");
                break; 
        }
        //输出结果:优良
//可以不写default
        int score = 10;
        switch (score) {
            case 10:
                NSLog(@"优");
                break;
            case 9:
                NSLog(@"良");
                break;
            case 8:
                NSLog(@"一般");
                break;
//            default:
//                NSLog(@"差");
//                break;
        }
        //输出结果: 优

//default的位置可以随便放
 int score = 10;
        switch (score) {
            default:
                NSLog(@"差");
                break;
            case 10:
                NSLog(@"优");
                break;
            case 9:
                NSLog(@"良");
                break;
            case 8:
                NSLog(@"一般");
                break;
            
        }
        //输出结果: 优
//在case中定义变量要加大括号,保证分隔作用域
int score = 9;
        switch (score) {
            case 10:
                NSLog(@"优");
                break;
            case 9: {  //在case中定义变量要加大括号,保证分隔作用域
                NSString *name = @"张三";
                NSLog(@"%@ 良",name);
                break;
            }
                
            case 8:
                NSLog(@"一般");
                break;
            default:
                NSLog(@"差");
                break;
        }
        //输出结果:
  • Swift代码
//不需要break,只要符合其中一个case的条件语句,就会跳出swich
let number = "10"  //可以定义任意数据类型
switch number {
case "10":
    print("优")
case "9": 
    print("良")
case "8":
    let name = "老王"   //这里定义变量可以不用大括号进行分隔
    print("\(name)一般")
default:
    print("差")
}
输出结果:优
//各个cese之间不能穿透,如果有多个值,可以使用","隔开
let number = "10"  //可以定义任意数据类型
switch number {
case "10", "9":   //注意OC是不能这样写的(各个cese之间不能穿透,如果有多个值,可以使用","隔开)
    print("优")
case "8":
    let name = "老王"   //这里定义变量可以不用大括号进行分隔
    print("\(name)一般")
default:
    print("差")
}
//输出结果: 优
//swich也可以使用区间运算
let number = 62
switch number {
case 1..<12:
    print("这个数的范围是1到12")
case 12..<100:
    print("这个数的范围是12到100")
case 100..<1000:
    print("这个数的范围是100到1000")
default:
    print("many")
}
//输出结果: 这个数的范围是12到100
//swich也可以用在元组里面,元组和区间并用
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("the point at the origin")
case (1, 0):
    print("(\(somePoint.0), 0) is on the x-axis")
case (0, 1):
    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 the box")
}
//输出结果:(1, 1) is inside the box
//"_"表明匹配所有可能的值   "_":通配符
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("the point at the origin")
case (_, 0):
    print("somePoint is on the x-axis")
case (0, _):
    print("somePoint is on the y-axis")
case (-2...2, -2...2):
    print("somePoint is inside the box")
default:
    print("somePoint is outside the point")
}
//输出结果:(1, 1) is inside the box
//值绑定(swich的case可以将匹配到的值绑定为一个临时的常量或者变量,来给case函数体使用)
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("the point at the origin")
case (let x, 0):  //会将somePoint中X的值赋值给X
    print("(\(somePoint.0), \(somePoint.1)) is on the x-axis, it is value is \(x)")
case (0, let y):
    print("on the y-axis with a value is \(y)")
case (let x, let y):  // 会将point中XY的值赋值给XY
    print("someWhere else at (\(x), \(y)) ")
//default:   //如果前面已经有匹配case的值了,没有省略default的话,这里会报一个警告(Default will never be executed,表示这个语句永远不会被执行)所以这里的default可以省略
//    print("somePoint is outside the point")
}
//输出结果: someWhere else at (1, 1) 
//swich case可以使用where分句来检查是否符合特定的约束(根据条件绑定)
let anotherPoint = (1, -1)
switch (anotherPoint) {
case let (x, y) where x == y:
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:  //只有where后面的条件表达式为真才赋值并执行case后的语句
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    print("(\(x), \(y)) is other point")
}
//输出结果: (1, -1) is on the line x == -y
//复合匹配
let someCharacter: Character = "e"
switch someCharacter {
case "a", "o", "e", "i", "u":   //使用“,”分隔多个值
    print("\(someCharacter) is a vowel") //vowel:元音
case "b", "c", "d", "f", "g", "h":
    print("\(someCharacter) is a consonant") //consonant:辅音
default:
    print("\(someCharacter) is not a vowel or a consonant")
}
//输出结果: e is a vowel
//复合值绑定
let anotherPoint = (9, 0)
switch anotherPoint {
case (let distence, 0), (0, let distence):    //元组加上值绑定,有多个值,使用了","隔开
    print("\(distence) from the origin")
default:
    print("no no no")
}
//输出结果: 9 from the origin
//fallthrough:如果需要C或者OC一样风格的贯穿行为,可以使用fallthrogh,只要使用了fallthrogh,不会立即跳出switch语句,后面的case条件语句一样会执行
let someCharacter: Character = "a"
switch someCharacter {
case "A":
    print("这个字母是大写的A")
    fallthrough
case "a":
    print("is the first letter of the alphabet")
    fallthrough
case "z":
    print("the last letter of the alphabet")
    fallthrough
default:
    print("no one letter")
}

//输出结果:  is the first letter of the alphabet
//          the last letter of the alphabet
//          no one letter
//语句标签:可以用语句标签来给循环语句或者条件语句做标记.
var number = 10
whileLoop: while number > 0 {
    switch number {
    case 9:
        print("9")
    case 10:
        var sum = 0
        for index in 1...10 {
            sum += index
            if index == 9 {
                print(sum)
                break whileLoop
            }
        }
    default:
        break
    }
    number -= 1
}
输出结果:45
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: `associatedtype` 和 `typealias` 在 Swift 都可以用来为类型起别名,但是它们之间有一些重要的区别。 `typealias` 可以为已知类型起别名,例如: ``` typealias MyString = String ``` `associatedtype` 主要用在协议,用来指定协议的实现使用的类型。例如: ``` protocol MyProtocol { associatedtype T func getT() -> T } ``` 在这个例子,协议 MyProtocol 声明了一个 associatedtype T,其实现类型可以是任何类型。 总之,`associatedtype` 更多的是在编写模板代码时使用,而 `typealias` 更多的是在给已知类型起别名时使用。 ### 回答2: 在Swift,`associatedtype`和`typealias`是用于类型别名的两个不同的关键字。 `typealias`关键字用于为现有的类型定义一个新的别名。例如,我们可以使用`typealias`来为已有的协议类型或者复杂的泛型类型定义一个新的短名称,以增加代码可读性。使用`typealias`时,我们需要提供新的别名和原始类型之间的等式关系。例如: ```swift typealias StringDictionary = Dictionary<String, String> ``` `associatedtype`关键字则用于协议声明一个关联类型。这意味着在定义协议时并不需要指定具体的类型,而是在实现该协议的类型指定关联类型。关联类型允许协议使用泛型,并使得实现该协议的类型可以根据需要提供合适的具体类型。关联类型使用`associatedtype`关键字定义,并在协议被声明。例如: ```swift protocol Container { associatedtype Item func addItem(item: Item) } class Stack<T>: Container { typealias Item = T func addItem(item: Item) { // 实现代码 } } ``` 在这个例子,`Container`协议使用`associatedtype`定义了一个关联类型`Item`,而在`Stack`类,我们使用`typealias`将泛型参数`T`赋值给了`Item`,从而实现了`Container`协议。 总结来说,`typealias`是用于创建类型别名,而`associatedtype`则是在协议定义关联类型,允许实现协议的类型提供具体的类型。 ### 回答3: 在Swift,`associatedtype`和`typealias`是两个用于定义类型别名的关键词。 `typealias`用于给现有类型创建一个新的别名。具体来说,它允许我们为一个已经存在的类型创建一个可读性更好的别名。这对于代码的可读性和维护性非常有帮助。例如,我们可以使用`typealias`来给某个复杂的闭包类型创建一个简化的别名: ```swift typealias CompletionHandler = (Bool) -> Void ``` 这将使我们能够在代码更容易地使用`CompletionHandler`这个类型,而不需要每次都书写长长的闭包类型。 而 `associatedtype`用于在协议定义一个关联类型。关联类型是一种协议的抽象类型,它表示在采纳该协议的类型需要提供的类型。具体来说,协议可以包含一个或多个关联类型的声明,而采纳该协议的类型需要根据实际情况提供具体的类型。这种方式可以让我们在协议声明与具体实现无关的抽象类型,以增加灵活性和可复用性。 举个例子,我们可以定义一个协议 `Container`,其包含一个关联类型 `Item`: ```swift protocol Container { associatedtype Item var count: Int { get } mutating func addItem(_ item: Item) subscript(index: Int) -> Item { get } } ``` 在采纳这个协议的类型,我们可以根据自己的需求来指定具体的类型,例如: ```swift struct Stack<Element>: Container { typealias Item = Element // ... } ``` 在这个例子,我们将 `Element` 作为 `Stack` 结构体的泛型类型,并指定 `Item` 的类型为 `Element`,符合 `Container` 协议的要求。 综上所述,`typealias`用于定义类型别名,而 `associatedtype`用于定义协议的抽象类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值