这篇文章主要给大家介绍了关于Swift枚举的一些小用法,文中通过示例代码介绍的非常详细,对大家学习或者使用Swift具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
前言
在 Swift 中,枚举是一个非常方便也非常强大的类型。我们在日常使用中也经常会使用到它。
例如,我们最常见的 optional:
enum Optional<T> {
 case Some(T)
 case None
}
这里不准备介绍枚举的基本用法,只是记录两个比较好用的枚举用法。
关联值
关联值是将额外信息附加到 enum case 中的一种极好的方式。
例如,当我们需要将一系列的值传到下一个类中时,一般情况下我们像下方代码一样写出几个设置的方法:
struct MyStruct {
  var value: Int
  init(_ value: Int?) {
    if let val = value {
      self.value = val
    } else {
      self.value = Int(INT_MAX)
    }
  }
}
class Two {
  var value1: String?
  var value2: Int?
  var value3: MyStruct?
  func setValue1(value: String?) { }
  func setValue2(value: Int?) { }
  func setValue2(value: MyStruct?) { }
}
这样当需要传的值变多时,代码无疑就会变得没那么好看了。我们可以用枚举来简化:
enum ValueBind {
  case bindStringValue(str: String)
  case bindIntValue(num: Int)
  case bindModel(model: MyStruct)
}
class Two {
  var value1: String?
  var value2: Int?
  var value3: MyStruct?
  func setValueBind(value: ValueBind) {
    switch value {
    case .bindStringValue(let str):
      print(str)
    case .bindModel(let model):
      print(model.value)
    case .bindIntValue(let num)
      print(num)
    }
  }
}
利用枚举关联值之后,咱们的代码马上就简洁了不少。
自定义枚举类型
平常我们使用枚举时,我们在为枚举定义 value 时,一般就只用了几种基本的类型:
enum Direction {
  case left
  case top
  case right
  case bottom
}
enum StringEnum: String {
  case hello = "hello"
  case world = "world"
}
enum IntEnum: Int {
  case one = 1
  case two = 2
}
但是,如果我们需要在枚举类型放入我们自定义的类型的话,我们就需要为枚举加一些东西了。
enum CustomEnum: RawRepresentable {
  typealias RawValue = MyStruct
  case null
  case one
  case two
  
  init?(rawValue: MyStruct) {
    switch rawValue.value {
    case 1:
      self = .one
    case 2:
      self = .two
    default:
      self = .null
    }
  }
  var rawValue: MyStruct {
    switch self {
    case .one:
      return MyStruct(1)
    case .two:
      return MyStruct(2)
    default:
      return MyStruct(nil)
    }
  }
}
我们让枚举遵守 RawRepresentable 协议,并实现协议的一些属性及方法:
/*
  将枚举的 RawValue 关联为自己希望的类型
**/
associatedtype RawValue
/*
  利用自己关联的类型生成枚举的实例
**/
init?(rawValue: Self.RawValue)
/*
  将自己定义的类型的作为 RawValue 返回
**/
var rawValue: Self.RawValue { get }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程学习网的支持。
本文标题为:Swift枚举的一些小用法总结
				
        
 
            
        基础教程推荐
- ruby-on-rails – Nginx支持的Rails应用程序中缺少Content-Length Header 2023-09-20
 - go语言的魔幻旅程14-反射 2023-09-05
 - R语言学习代码格式一键美化 2022-12-05
 - Go语言实现一个Http Server框架(二) Server的抽象 2023-07-25
 - R语言histogram(直方图)的具体使用 2022-10-28
 - R语言关联规则深入详解 2022-11-08
 - R语言使用gganimate创建可视化动图 2022-12-10
 - golang 自然语言处理工具(gohanlp) 2023-09-05
 - Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
 - R语言多元线性回归实例详解 2022-12-15
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				