作为斯威夫特的新手,这就是我发现的:
enum HttpMethod {
static let post = "POST"
static let get = "GET"
}
// can assign to string property.
request.httpMethod = HttpMethod.post // --> "POST"在阅读了enum之后,使用没有案例的struct而不是struct的原因对我来说是有意义的,但这并不是我感兴趣的东西。
有一个强大的C#背景--这就是我实现它的方法:
enum HttpMethod: String {
case post = "POST"
case get = "GET"
}
// I'd even consider this alternatively:
enum HttpMethod: String {
case post
case get
}
// Must retrieve string value
request.httpMethod = HttpMethod.post.rawValue // --> "POST" or "post"第二个版本需要使用rawValue,但它将枚举作为一个真正的枚举。来自C#的我习惯于在枚举值上使用.ToString()。
这只是个人偏好和斯威夫特使用无案例枚举而不是实际案例+ rawValue的惯例,还是还有其他(技术)原因更倾向于第一个版本而不是第二个版本?
发布于 2018-03-22 11:53:04
案卷
最好在以下场景中创建一个包含案例的枚举:
enum的优势是:
静态值:
当在框架中定义了struct / class并希望对其进行扩展以添加更多的值时。
使用此方法的示例是Notification.Name in Foundation。
注意:
结论
enumstatic值。enum中使用它,您可以将其定义为struct,以便更清楚地说明其意图。发布于 2018-03-22 11:48:20
是否对字符串值使用枚举取决于您要解决的问题。如果需要一组无界字符串情况,最好使用单个let rawValue: String属性声明一个结构,对于已知值,最好声明已知值的静态实例。这就是苹果框架对NSNotification.Name这样的东西所做的事情。
关于枚举rawValue的侧边栏:使用:String声明的枚举自动为CustomStringConvertible (类似于.toString()),使用"\(enum-name)"而不是.rawValue,但在枚举的情况下打印它,而不是字符串。有时,当我需要的时候,我会实现CustomStringConvertible来打印rawValue。
发布于 2022-11-07 19:26:02
我确实同意这样做比不适用于案例要好。无实例枚举用于存储常量的另一个原因是。决定如何存储常量可能会变得很棘手。无实例枚举提供了一种无法实例化/构造的类型。它只是列出静态常量属性的一种方法,可以像枚举一样访问这些属性。
enum Constants {
static let dateFormat: String = "dd.MM.yy"
static let timeFormat: String = "hh:mm:ss a"
static let defaultLocationCoordinates: CLLocationCoordinate2D = CLLocationCoordinate2DMake(-26.204103, 28.047305)
}
class Test {
static func echo() {
print("\(Constants.dateFormat)")
print("\(Constants.timeFormat)")
print("\(Constants.defaultLocationCoordinates)")
}
}https://stackoverflow.com/questions/49427144
复制相似问题