source

Swift에서 유형에 대해 표시되는 텍스트 표현을 변경하려면 어떻게 해야 합니까?

ittop 2023. 7. 31. 21:55
반응형

Swift에서 유형에 대해 표시되는 텍스트 표현을 변경하려면 어떻게 해야 합니까?

문자열 보간에 표시되는 텍스트 출력을 수정하려면 어떻게 해야 합니까?

Printable프로토콜이 가장 명확하게 보이지만 문자열 보간과 인스턴스를 인쇄할 때 모두 무시됩니다. 예:

struct Point : Printable
{
    var x = 0
    var y = 0

    var description : String {
        return "(\(x), \(y))"
    }

    func toString() -> String {
        return description
    }
}

마찬가지로toString()규약도 영향을 미치지 않습니다.

var p = Point(x: 10, y: 20)

println(p)                   // V11lldb_expr_05Point (has 2 children)
println("\(p)")              // V11lldb_expr_05Point (has 2 children)
println(p.description)       // (10, 20)
println("\(p.description)")  // (10, 20)

구조체에 대해 자체 문자열 표현을 사용하는 PlayGround에서는 동작이 다시 다릅니다.

p // {x 10, y 20}

인스턴스 표시 방법을 변경할 수 있는 방법이 있습니까?

스위프트 2 - 4

요약

에 부합합니다.CustomStringConvertible프로토콜 및 추가description:

var description: String {
    return "description here"
}

일부 구조체를 작성할 수 있습니다.

struct Animal : CustomStringConvertible {
    let type : String

    var description: String {
        return type
    }
}

struct Farm : CustomStringConvertible {
    let name : String
    let animals : [Animal]

    var description: String {
        return "\(name) is a \(self.dynamicType) with \(animals.count) animal(s)."
    }
}

초기화하는 경우:

let oldMajor = Animal(type: "Pig")
let boxer = Animal(type: "Horse")
let muriel = Animal(type: "Goat")

let orwellsFarm = Farm(name: "Animal Farm", animals: [oldMajor, boxer, muriel])

사용자 지정 설명이 놀이터에 나타납니다.

enter image description here

참고 항목CustomDebugStringConvertible디버깅하는 동안 더 자세한 출력에 사용할 수 있습니다.


사용 참고 사항

초기화할 수 있습니다.String이 프로토콜을 구현하지 않고 모든 유형에서 사용할 수 있습니다.예:

enter image description here

이러한 이유로 문서에는 다음과 같은 내용이 있습니다.

사용.CustomStringConvertible일반적인 제약 조건으로 또는 적합한 형식의 액세스description따라서 직접적으로, 낙담합니다.

관련 Apple Swift 문서

Apple은 다음과 같은 예를 제공합니다.

struct MyType: Printable {
    var name = "Untitled"
    var description: String {
        return "MyType: \(name)"
    }
}

let value = MyType()
println("Created a \(value)")
// prints "Created a MyType: Untitled"

만약 당신이 이것을 놀이터에서 시도한다면, 당신이 받는 것과 같은 문제가 생길 것입니다.V11lldb_expr...) 놀이터에서는 이니셜라이저를 호출하면 오른쪽에 설명이 나오지만,println읽을 만한 것을 반환하지 않습니다.

그러나 놀이터 밖에서는 이 코드가 예상대로 작동합니다.당신의 코드와 위의 애플사의 샘플 코드가 모두 정확하게 인쇄됩니다.description비플레이그라운드 컨텍스트에서 사용할 경우.

저는 당신이 놀이터에서 이 행동을 바꿀 수 있다고 생각하지 않습니다.그것은 또한 그냥 벌레일 수도 있습니다.

편집: 저는 이것이 버그라고 확신합니다. 저는 Apple에 버그 보고서를 제출했습니다.

업데이트: Swift 2에서 대신Printable,사용하다CustomStringConvertible(문서 링크 참조).

struct MyType: CustomStringConvertible {
    var name = "Untitled"
    var description: String {
        return "MyType: \(name)"
    }
}

let value = MyType()
println("Created a \(value)")
// prints "Created a MyType: Untitled"

이것은 놀이터의 벌레로 보입니다.프로그램을 실제로 컴파일하고 정상적으로 실행하면 다음과 같이 출력됩니다.

(10, 20)
(10, 20)
(10, 20)
(10, 20)

역시

https://bugreport.apple.com 에서 보고해야 합니다.

AppCode를 제공합니다.Generate| debugDescription그리고 '''설명 생성'''. 멤버가 많은 구조체에 대해 타이핑하는 것보다 낫습니다.

enter image description here

Swift 5+의 대안으로 String을 확장할 수 있습니다.문자열 보간

struct Point {
    var x : Int
    var y : Int
}

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Point) {
        appendInterpolation("\(value.x):\(value.y)")
    }
}

다음 값이 변경됩니다.print("\(p)")하지만 때문은 아닙니다.print(p)여전히 그 설명을 사용할 것입니다.

swift 5를 구현하면 .CustomStringConvertible(https://developer.apple.com/documentation/swift/customstringconvertible/1539130-description) 을 참조하십시오.

콘솔 보기: 보기 -> 보조 편집기 -> 보조 편집기 표시를 열면 예상되는 인쇄 줄을 볼 수 있습니다. xCode 6.3.2에서 Yosimite 10.10으로 체크인됨

enter image description here

언급URL : https://stackoverflow.com/questions/24068506/how-can-i-change-the-textual-representation-displayed-for-a-type-in-swift

반응형