美文网首页
swift 模式匹配

swift 模式匹配

作者: 莫寂岚 | 来源:发表于2019-03-30 16:55 被阅读0次

    写swift一时爽,一直写一直爽~~~


    模式匹配

    switt中强大的switch case 结合枚举和元祖会有意想不到的作用
    枚举:

    // 定义个枚举
    enum School {
      case Student(name: String, age: Int, address: String?)
      case Teacher(name: String, age: Int, address: String?)
    }
    // 取一个枚举值
    let karl =  School.Student(name: "karl", age: 27, address: "AH")
    
    // 匹配一下
    switch student {
    case .Student(let name, let age, let address):
      print("\(name) -- \(age) -- \(address)")
    default:
      break
    }
    

    通配符

    这个有意思,和可选链有点混

    let student = School.Student(name: "karl", age: 27, address: nil)
    let teacher = School.Teacher(name: "wang", age: 50, address: "AH")
    
    // _ :这个值完全不重要,可有可无,是什么我都不关心。
    switch student {
    case let .Teacher(name, _, _):
        print("name: \(name)")
    default: break
    } 
    
    // _? :这个值我虽然不用,但是它不能为空
    switch student {
    case let .Student(name, age, _?):
       print("name: \(name)")
    default: break
    } 
    

    元祖

    吆西,看完上面的概念,来看看元祖‘

    // 不管age, 取出name
    let people = (age: 27, name: "karl")
    switch people {
    case (_, let name):
      print(name)
    default:
      break
    }
    // where 语句
    switch student {
    case let .Student(_, age, _) where age > 30:
      print("\(age)")
    default:
      break
    }
    

    other

    // 来个range看看,爽不爽
    let number = 10
    switch number {
    case 0 ... 7:
      print("0 ... 7")
    case 10 ..< 20:
      print("10 ..< 20")
    default:
      break
    }
    

    参考文章

    相关文章

      网友评论

          本文标题:swift 模式匹配

          本文链接:https://www.haomeiwen.com/subject/rlrsbqtx.html