Reputation: 31985
I want to initiate an Array of Dictionary in Swift, where the value of one of keys is of type UIColor
. So I want to create the following Array:
var myArr:[[String: Any]] = [
["name": "mark", "age": "30", "color": UIColor.blackColor()]
]
However, the code above returns an AssertString is not convertible to UIColor
error. But the Any
should be used in UIColor
, I don't know why it returns such errors nor what it means.
So how can I resolve the issue and use UIColor
instance properly?
Sorry but I found that the actual error was not on the snippet above - it is on the following part, which is from my own UIColor
extension:
["name": "pete", "age" "25", "color": UIColor(R:245.0, G:168.0, B:13.0, A:1.0)]
And I created a separate file named UIColor+ColorWithInt.swift
(not sure about the proper name convention, but I've been just porting my old Objective-C app to Swift, which is the reason I used Dictionary
to represent the data above).
import Foundation
import UIKit
extension UIColor {
func colorWithR(R: CGFloat, G: CGFloat, B: CGFloat, A: CGFloat) -> UIColor {
return UIColor(red: (R/255), green: (G/255), blue: (B/255), alpha: A)
}
}
Upvotes: 2
Views: 2257
Reputation: 21013
As mentioned in my comment, I'd suggest using a struct or some other concrete data structure for this scenario.
import UIKit
struct Person {
var name: String
var age: Int
var color: UIColor
}
var myArr:[Person] = [
Person(name: "mark", age: 30, color: UIColor.blackColor())
]
Or as a class...
class Person {
var name: String
var age: Int
var color: UIColor
init(name: String, age: Int, color: UIColor) {
self.name = name
self.age = age
self.color = color
}
}
var myArr:[Person] = [
Person(name: "mark", age: 30, color: UIColor.blackColor())
]
RE: UPDATE
I think you want something like this...
extension UIColor {
convenience init(R: CGFloat, G: CGFloat, B: CGFloat, A:CGFloat) {
self.init(red: (R/255.0), green: (G/255.0), blue: (B/255.0), alpha: A)
}
}
var red = UIColor(R: 255, G: 0, B: 0, A: 1)
Upvotes: 2