sourcecode

Swift에서 열거값 이름을 얻는 방법은 무엇입니까?

codebag 2023. 4. 13. 20:48
반응형

Swift에서 열거값 이름을 얻는 방법은 무엇입니까?

raw로 하면 raw가 Integer§:

enum City: Int {
  case Melbourne = 1, Chelyabinsk, Bursa
}

let city = City.Melbourne

「 」를 해야 ?city에 값Melbourne이 언어에서 이런 유형의 이름 인스펙션을 사용할 수 있습니까?

(이 코드는 동작하지 않습니다):

println("Your city is \(city.magicFunction)")
> Your city is Melbourne

7 5 버전 2)부터는Xcode 7 7 5 ( Swift 버 2)를 할 수 .print(_:)또는 로 변환합니다.String를 사용합니다.String의 »init(_:)이니셜라이저 또는 문자열 보간 구문.예를 들어 다음과 같습니다.

enum City: Int {
    case Melbourne = 1, Chelyabinsk, Bursa
}
let city = City.Melbourne

print(city)
// prints "Melbourne"

let cityName = "\(city)"   // or `let cityName = String(city)`
// cityName contains "Melbourne"

따라서 문자열 리터럴을 반환하기 위해 각 케이스를 켜는 편리한 함수를 정의하고 유지할 필요가 없어졌습니다.또한 raw-value 유형이 지정되지 않은 경우에도 모든 열거에 대해 자동으로 작동합니다.

debugPrint(_:)&String(reflecting:)할 수 .

debugPrint(city)
// prints "App.City.Melbourne" (or similar, depending on the full scope)

let cityDebugName = String(reflecting: city)
// cityDebugName contains "App.City.Melbourne"

다음의 각 시나리오에서 인쇄되는 것을 커스터마이즈 할 수 있습니다.

extension City: CustomStringConvertible {
    var description: String {
        return "City \(rawValue)"
    }
}

print(city)
// prints "City 1"

extension City: CustomDebugStringConvertible {
    var debugDescription: String {
        return "City (rawValue: \(rawValue))"
    }
}

debugPrint(city)
// prints "City (rawValue: 1)"

(예를 들어 "The city is Melbourn"을 출력할 때 스위치 문에 의존하지 않고 이 "default" 값을 호출할 수 있는 방법을 찾지 못했습니다.「」를 사용합니다.\(self)description/debugDescription을 참조해 주십시오.)


String의 »init(_:)&init(reflecting:)이니셜라이저는 리플렉트된 타입이 무엇을 준수하느냐에 따라 인쇄되는 것을 정확하게 나타냅니다.

extension String {
    /// Initialize `self` with the textual representation of `instance`.
    ///
    /// * If `T` conforms to `Streamable`, the result is obtained by
    ///   calling `instance.writeTo(s)` on an empty string s.
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
    ///   result is `instance`'s `description`
    /// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
    ///   the result is `instance`'s `debugDescription`
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(reflecting: T)`
    public init<T>(_ instance: T)

    /// Initialize `self` with a detailed textual representation of
    /// `subject`, suitable for debugging.
    ///
    /// * If `T` conforms to `CustomDebugStringConvertible`, the result
    ///   is `subject`'s `debugDescription`.
    ///
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the result
    ///   is `subject`'s `description`.
    ///
    /// * Otherwise, if `T` conforms to `Streamable`, the result is
    ///   obtained by calling `subject.writeTo(s)` on an empty string s.
    ///
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(T)`
    public init<T>(reflecting subject: T)
}


이 변경에 대한 자세한 내용은 릴리스 노트를 참조하십시오.

현재 열거된 사례에 대한 자기 성찰은 없다.각각 수동으로 선언해야 합니다.

enum City: String, CustomStringConvertible {
    case Melbourne = "Melbourne"
    case Chelyabinsk = "Chelyabinsk"
    case Bursa = "Bursa"

    var description: String {
        get {
            return self.rawValue
        }
    }
}

raw 타입을 Int로 할 필요가 있는 경우는, 직접 스위치를 실행할 필요가 있습니다.

enum City: Int, CustomStringConvertible {
  case Melbourne = 1, Chelyabinsk, Bursa

  var description: String {
    get {
      switch self {
        case .Melbourne:
          return "Melbourne"
        case .Chelyabinsk:
          return "Chelyabinsk"
        case .Bursa:
          return "Bursa"
      }
    }
  }
}

Swift-3(Xcode 8.1로 테스트 완료)에서는 다음 메서드를 열거형에 추가할 수 있습니다.

/**
 * The name of the enumeration (as written in case).
 */
var name: String {
    get { return String(describing: self) }
}

/**
 * The full name of the enumeration
 * (the name of the enum plus dot plus the name as written in case).
 */
var description: String {
    get { return String(reflecting: self) }
}

그런 다음 열거형 인스턴스에서 일반 메서드 호출로 사용할 수 있습니다.이전 Swift 버전에서도 동작할 수 있을 것 같습니다만, 아직 테스트해 본 적은 없습니다.

이 예에서는 다음과 같습니다.

enum City: Int {
    case Melbourne = 1, Chelyabinsk, Bursa
    var name: String {
        get { return String(describing: self) }
    }
    var description: String {
        get { return String(reflecting: self) }
    }
}
let city = City.Melbourne

print(city.name)
// prints "Melbourne"

print(city.description)
// prints "City.Melbourne"

모든 Enum에 이 기능을 제공하는 경우 확장으로 할 수 있습니다.

/**
 * Extend all enums with a simple method to derive their names.
 */
extension RawRepresentable where RawValue: Any {
  /**
   * The name of the enumeration (as written in case).
   */
  var name: String {
    get { return String(describing: self) }
  }

  /**
   * The full name of the enumeration
   * (the name of the enum plus dot plus the name as written in case).
   */
  var description: String {
    get { return String(reflecting: self) }
  }
}

이것은 Swift enums에만 적용됩니다.

String(describing:) initializer가 string rawValues의 할 수 있습니다.

enum Numbers: Int {
    case one = 1
    case two = 2
}

let one = String(describing: Numbers.one) // "one"
let two = String(describing: Numbers.two) // "two"

enum이 다음 명령어를 사용하는 경우 이 기능은 작동하지 않습니다.@objc★★★★★★★★★★★★★★★★★★:

된 Swift 는 Objective-C "Swift" 가 되어 있지 수 .@objc, 에 정의되어 있기 에 위와같이 하지 않습니다그럼에도 불구하고 이러한 Enums는 목표 C에 정의되어 있기 때문에 위와 같이 작동하지 않는다.

enum예를 들어, 를 어 들 일 재 법 음 것 이 거 는 확 way, s seems currently장 example be, with to for열하 only the를다같니입CustomStringConvertible그런대로 끝나다결국 다음과 같은 결과가 됩니다.

extension UIDeviceBatteryState: CustomStringConvertible {
    public var description: String {
        switch self {
        case .Unknown:
            return "Unknown"
        case .Unplugged:
            return "Unplugged"
        case .Charging:
            return "Charging"
        case .Full:
            return "Full"
        }
    }
}

And then casting the 그리고 캐스팅은enum as ~하듯이String::::

String(UIDevice.currentDevice().batteryState)

Swift 2.2의 Enum에 대한 String(…)(CustomStringConvertible) 지원 외에 이러한 Enum에 대한 리플렉션 지원도 다소 중단되었습니다.연관된 값이 있는 열거형 케이스의 경우 리플렉션(reflection)을 사용하여 열거형 케이스의 라벨을 얻을 수 있습니다.

enum City {
    case Melbourne(String)
    case Chelyabinsk
    case Bursa

    var label:String? {
        let mirror = Mirror(reflecting: self)
        return mirror.children.first?.label
    }
}

print(City.Melbourne("Foobar").label) // prints out "Melbourne"

하지만, 다 진 은 는 " 것 러 의 하 고 위 있 의 반 해 한 순 것 근 다, meant에 broken by beinglabel computed property just returns 계산된 속성이 반환됨nil(부-후)

print(City.Chelyabinsk.label) // prints out nil

Swift 3 swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift 。, 은 「일단」입니다.String(…)중 와 같이)

print(String(City.Chelyabinsk)) // prints out Cheylabinsk

이 질문에 부딪혔는데, 앞서 언급한 기능을 만드는 간단한 방법을 알려드리고 싶습니다.

enum City: Int {
  case Melbourne = 1, Chelyabinsk, Bursa

    func magicFunction() -> String {
        return "\(self)"
    }
}

let city = City.Melbourne
city.magicFunction() //prints Melbourne

이제 Swift에는 암묵적으로 할당된 원시 값이 있습니다.기본적으로 각 케이스에 raw 값을 지정하지 않고 열거형이 String인 경우 케이스의 raw 값이 문자열 형식인 것으로 추정됩니다.한 번 해봐.

enum City: String {
  case Melbourne, Chelyabinsk, Bursa
}

let city = City.Melbourne.rawValue

// city is "Melbourne"

너무 아쉽다.

이러한 이름이 필요한 경우(컴파일러는 정확한 철자를 알고 있지만 접근을 거부합니다(Swift team 감사합니다!!). String을 열거의 기반으로 하지 않거나 할 수 없는 경우)는 다음과 같습니다.

enum ViewType : Int, Printable {

    case    Title
    case    Buttons
    case    View

    static let all = [Title, Buttons, View]
    static let strings = ["Title", "Buttons", "View"]

    func string() -> String {
        return ViewType.strings[self.rawValue]
    }

    var description:String {
        get {
            return string()
        }
    }
}

위의 내용은 다음과 같이 사용할 수 있습니다.

let elementType = ViewType.Title
let column = Column.Collections
let row = 0

println("fetching element \(elementType), column: \(column.string()), row: \(row)")

그리고 예상된 결과를 얻을 수 있습니다(비슷하지만 표시되지 않는 컬럼 코드).

fetching element Title, column: Collections, row: 0

저는 에서음음, 음음음음음음음음 the the the the the the the the the를 .description은 refer속 the the에 된다.string 」, 「 」, 「 」라고 불리는 것에 주의해 .static컴파일러가 너무 건망증이 심해서 콘텍스트를 모두 호출할 수 없기 때문에 변수는 해당 엔클로저 타입의 이름으로 스코프 수식되어야 합니다.

을 사용하다이 할 수 없다는 .enumerate할 수 것enumerate' '시퀀스'는 켜지지 .enum!

Swift의 경우:

extension UIDeviceBatteryState: CustomStringConvertible {

    public var description: String {
        switch self {
        case .unknown:
            return "unknown"
        case .unplugged:
            return "unplugged"
        case .charging:
            return "charging"
        case .full:
            return "full"
        }
    }

}

변수 "batteryState"의 경우 다음 번호로 문의합니다.

self.batteryState.description

Swift Enums에서의 자기성찰은 부분적으로 효과가 있는 것 같습니다.

@drewag의 응답을 보니 Xcode 11.5의 Swift 5.X에서 rawValues가 없는 Enum이 실제로 자기성찰이 가능합니다.이 코드는 동작합니다.

public enum Domain: String {
    case network
    case data
    case service
    case sync
    var description: String {
        return "\(self)"     // THIS INTROSPECTION WORKS
    }
}
enum ErrorCode: Int, CustomStringConvertible {
    case success = 200
    case created = 201
    case accepted = 202
    case badRequest = 400
    case unauthorized = 401
    case forbidden = 403
    case notFound = 404
    var code: Int {
        return self.rawValue
    }
    var description: String {
        return "\(self)"      //THIS DOES NOT WORK - EXEC_BAD_ACCESS
    }
}
let errorCode = ErrorCode.notFound
let domain = Domain.network
print(domain.description, errorCode.code, errorCode.description)

「 「 」를 교환해 ."\(self)"★★★★★★에"string" Enum 문자열이.404호

사용방법: " " "String(self)"\(self)" in the first will require the Enum to conform to theLossless String Convertible (손실 없는 문자열 변환 가능)따라서 문자열 보간은 좋은 회피책으로 보입니다.

를 추가하려면var description: String문을 문은 Enum보다 앞에 를 가리킵니다.앞으로 지적된 바와 같이 모든 Enum 케이스가 표시됩니다.

var description: String {
    switch self {
    case .success: return "Success"
    case .created: return "Created"
    case .accepted: return "Accepted"
    }
}

간단하지만 작동...

enum ViewType : Int {
    case    Title
    case    Buttons
    case    View
}

func printEnumValue(enum: ViewType) {

    switch enum {
    case .Title: println("ViewType.Title")
    case .Buttons: println("ViewType.Buttons")
    case .View: println("ViewType.View")
    }
}

언급URL : https://stackoverflow.com/questions/24113126/how-to-get-the-name-of-enumeration-value-in-swift

반응형