스위프트 : 열거 형 값을 문자열로 변환 하시겠습니까?
다음 열거가 주어지면 :
enum Audience {
case Public
case Friends
case Private
}
아래 상수 에서 문자열 "Public"
을 어떻게 얻 audience
습니까?
let audience = Audience.Public
이 기능이 어떤 Swift 버전에 추가되었는지 확실하지 않지만 현재 ( Swift 2.1 )에는 다음 코드 만 필요합니다.
enum Audience : String {
case public
case friends
case private
}
let audience = Audience.public.rawValue // "public"
원시 값에 문자열을 사용하는 경우 각 케이스의 내재 된 값 은 해당 케이스 이름 의 텍스트입니다 .
[...]
enum CompassPoint : String { case north, south, east, west }
위의 예에서 CompassPoint.south는 "south"등의 암시 적 원시 값을 갖습니다.
rawValue 속성을 사용하여 열거 사례의 원시 값에 액세스합니다.
let sunsetDirection = CompassPoint.west.rawValue // sunsetDirection is "west"
'문자열 얻기'에 대한 관용적 인터페이스는 CustomStringConvertible
인터페이스 를 사용 하고 description
getter에 액세스하는 것 입니다. 다음 enum
과 같이 정의하십시오 .
enum Foo : CustomStringConvertible {
case Bing
case Bang
case Boom
var description : String {
switch self {
// Use Internationalization, as appropriate.
case .Bing: return "Bing"
case .Bang: return "Bang"
case .Boom: return "Boom"
}
}
}
실제로 :
> let foo = Foo.Bing
foo: Foo = Bing
> println ("String for 'foo' is \(foo)"
String for 'foo' is Bing
업데이트 : 스위프트> = 2.0의 교체 Printable
와 함께CustomStringConvertible
참고 : 사용CutomStringConvertible
allows Foo
to adopt a different raw type. For example enum Foo : Int, CustomStringConvertible { ... }
is possible. This freedom can be useful.
지금은 열거 형을 다음과 같이 재정의합니다.
enum Audience: String {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
}
내가 할 수 있도록 :
audience.toRaw() // "Public"
그러나이 새로운 열거 정의가 중복되지 않습니까? 초기 열거 정의를 유지하고 다음과 같이 할 수 있습니까?
audience.toString() // "Public"
나는 Printable
함께 사용 하고 싶다Raw Values
.
enum Audience: String, Printable {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
var description: String {
return self.rawValue
}
}
그런 다음 우리는 할 수 있습니다 :
let audience = Audience.Public.description // audience = "Public"
또는
println("The value of Public is \(Audience.Public)")
// Prints "The value of Public is Public"
스위프트 3에서는 이것을 사용할 수 있습니다
var enumValue = Customer.Physics
var str = String(describing: enumValue)
...에서 Swift how to use enum to get string value
Xcode 7 GM 릴리스 용으로 업데이트되었습니다. 지금은 애플이 고맙게 생각하는대로 작동합니다!
enum Rank:Int {
case Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
let r = Rank.Ace
print(r) // prints "Ace"
print("Rank: \(r)!") // prints "Rank: Ace!"
It couldn't get simpler than this in Swift 2 and the latest Xcode 7 (no need to specify enum type, or .rawValue, descriptors etc...)
Swift 3 및 Xcode 8 용으로 업데이트되었습니다.
enum Audience {
case Public
case Friends
case Private
}
let audience: Audience = .Public // or, let audience = Audience.Public
print(audience) // "Public"
"Swift Programming Language"의 "Swift Tour"장에서 예제를 읽고 simpleDescription () 메소드를 단순화하는 방법을 찾고있는 사람은 enum 자체를 String으로 변환하여 수행 String(self)
할 수 있습니다.
enum Rank: Int
{
case Ace = 1 //required otherwise Ace will be 0
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace, .Jack, .Queen, .King:
return String(self).lowercaseString
default:
return String(self.rawValue)
}
}
}
Enum에서 Ints를 사용하는 경우 빠른 3 이상 예제
public enum ECategory : Int{
case Attraction=0, FP, Food, Restroom, Popcorn, Shop, Service, None;
var description: String {
return String(describing: self)
}
}
let category = ECategory.Attraction
let categoryName = category.description //string Attraction
After try few different ways, i found that if you don't want to use:
let audience = Audience.Public.toRaw()
You can still archive it using a struct
struct Audience {
static let Public = "Public"
static let Friends = "Friends"
static let Private = "Private"
}
then your code:
let audience = Audience.Public
will work as expected. It isn't pretty and there are some downsides because you not using a "enum", you can't use the shortcut only adding .Private neither will work with switch cases.
There are multiple ways to do this. Either you could define a function in the enum which returns the string based on the value of enum type:
enum Audience{
...
func toString()->String{
var a:String
switch self{
case .Public:
a="Public"
case .Friends:
a="Friends"
...
}
return a
}
Or you could can try this:
enum Audience:String{
case Public="Public"
case Friends="Friends"
case Private="Private"
}
And to use it:
var a:Audience=Audience.Public
println(a.toRaw())
참고URL : https://stackoverflow.com/questions/24701075/swift-convert-enum-value-to-string
'programing tip' 카테고리의 다른 글
보고서를 작성할 때 "보고서 데이터"창이 표시되지 않는 이유는 무엇입니까? (0) | 2020.07.22 |
---|---|
System.Drawing.Color를 RGB 및 16 진수 값으로 변환 (0) | 2020.07.22 |
JavaScript를 사용하여 요소를 어떻게 스크롤합니까? (0) | 2020.07.22 |
android : DrawableRight를 사용하여 버튼 및 TextViews에서 VectorDrawable을 사용할 수 있습니까? (0) | 2020.07.22 |
중요한 스타일 재정의 (0) | 2020.07.22 |