다음 코드 조각이 있습니다. MyDisplayable
에는 3 개의 옵션 String
이 있으며, 확장을 통한 프로토콜의 기본 구현이 있습니다. 내 질문은, 확장에서 3 개의 문자열을 반환한다고 확신하기 때문에 비 선택적으로 사용할 수있는 방법이 있습니까? 다른 구현으로 덮어 쓰면 위험 할 수 있습니다. (아래 코드의 질문 1과 2 참조)선택적 읽기 전용 변수에 대한 스위프트 프로토콜 기본 구현
고마워요!
protocol MyDisplayable {
var displayName: String? { get }
var shortDescription: String? { get }
var longDescription: String? { get }
}
protocol MyObject : MyDisplayable, CustomStringConvertible {
}
extension MyObject {
var displayName: String? {
return "noname"
}
var shortDescription: String? {
return "something can't be described"
}
var longDescription: String? {
return "no way to describe it further"
}
var description: String {
// **1. is there a way to use the strings as if they are non-optional?**
// **2. is it a problem if another class implements the protocol and returns `nil` for any of the strings, but here they are force unwrapped?**
return "\(displayName!): \(shortDescription!)\n\(longDescription!)"
}
}
class Something : MyObject {
}
let something = Something()
print("Something: \(something)")
만약 내가 당신이라면 나는 그런 것들을 복잡하게 만들지 않을 것입니다; 이 특정 문제를 해결하는 대신 목표 달성을위한 다른 방법을 찾아야합니다. 강타 주위에서 길을 해킹하면 가끔 컴파일러에서 무거워지는 것 외에도 상황이 악화됩니다. 아마 당신은 *'MyObject'없이 * 할 수 있고, 단지'MyDisplayable'에 옵션이 아닌 문자열을 기본 값으로 제공 할 수 있습니다. – user1244109