3
votes

I'm a longtime Obj-C developer but am new to Swift, like everyone else, and scratching my head at this one. I'm trying to convert an older tutorial that was written in Obj-C.

I have an "Animal" class declared like so:

class Animal
{
    let title: String
    let image: UIImage
    let creator: String

    init(title: String, image: UIImage, creator: String)
    {
       self.title = title
       self.image = image
       self.creator = creator
    }
}

And in another class, I want an array of Animal instances, which is declared as a property of that class like so:

let animals: [Animal]

And initialized (unsuccessfully) like so:

animals = [Animal(title: "Sleeping Cat", image: UIImage.imageNamed("ID-101.jpg") 
creator:"papaija2008"),
...
...
]

I am getting a build error in the first line of this array initializer, which reads just like the title of the post: "Type String does not conform to protocol StringLiteralConvertible". Can we not assign string literals to String objects? That seems impossible. What rule am I violating and how do I fix this?

Thanks in advance!

1
I've seen this error come up a lot, and it usually doesn't mean that something specifically string-related is wrong. Often, some parameter you're passing to a function is in some way improper. I've resolved issues like this by using a let with an explicit type for each relevant parameter and then passing in those variables. The compiler will generally give a more helpful error message that way. - Bill

1 Answers

3
votes

Using UIImage(named:) instead of UIImage.imageNamed() works for me:

let animals: [Animal] = [Animal(title: "Sleeping Cat", image: UIImage(named: "ID-101.jpg"), creator:"papaija2008")]

I hope it works for you too.