다음 코드를 고려하십시오.
protocol Color {
var color: UIColor { get }
}
struct Ball : Color {
var color: UIColor
}
let ball = Ball(color: .white)
print(ball)
이것은 효과가 있으며 결과는 다음과 같습니다.
Ball(color: UIExtendedGrayColorSpace 1 1)
이제 프로토콜에서 색상 배열이 주어지고 해당 색상으로 항목 배열 (공 또는을 준수하는 다른 유형)을 반환하는 함수를 만들고 싶습니다 Color
.
extension Color {
func multipleColors(colors: [UIColor]) -> [Color] {
var coloredItems = [Color]()
for item in colors {
// What do I put here ???
}
return coloredItems
}
}
그리고:
let coloredBalls = ball.multipleColors(colors: [.red, .green, .blue])
괄호 안에 무엇을 넣어야할지 모르겠습니다. 예를 들어 (말장난 없음), 내가 시도하면 :
coloredItems.append(Color(color: item))
오류는 다음과 같습니다.
'Color' cannot be constructed because it has no accessible initializers
그런 다음 프로토콜에 init 메서드를 추가했고 오류가 다음과 같이 변경되었습니다.
protocol type 'Color' cannot be instantiated
이 문제를 어떻게 해결합니까?
Color(color: item)
불가능한 프로토콜의 인스턴스를 만들려고 합니다.
아래에서 가능한 한 가지 일반적인 솔루션을 찾으십시오. 지금까지 비 정적 (좋은) 솔루션을 찾을 수 없습니다.
protocol Color {
var color: UIColor {get set}
init(color: UIColor)
}
struct Ball : Color {
var color: UIColor
}
extension Color {
static func item<T:Color>(_ item: T, inColors colors: [UIColor]) -> [T] {
var coloredItems = [T]()
for color in colors {
let newColoredItem = T.init(color: color)
coloredItems.append(newColoredItem)
}
return coloredItems
}
}
let ball = Ball(color: .white)
let coloredBalls = type(of:ball).item(ball, inColors: [.red, .green, .blue])
print(coloredBalls)
인쇄물:
[Ball(color: UIExtendedSRGBColorSpace 1 0 0 1), Ball(color: UIExtendedSRGBColorSpace 0 1 0 1), Ball(color: UIExtendedSRGBColorSpace 0 0 1 1)]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다