Hi guys!
I want to know how can I create an array of UIImage elements and then access these elements randomly?
I tried several times, but I have this issue:
Can someone help me?
Hi guys!
I want to know how can I create an array of UIImage elements and then access these elements randomly?
I tried several times, but I have this issue:
Can someone help me?
As you can see from the error Xcode/Playgrounds is providing, the problem here is that your function getElements()
is expecting to return a UIImage
, yet you are returning a String
. Additionally, the initialiser UIImage(named:)
is expecting a string, but you're passing in an image.
This can be fixed in one of two ways:
1 - Rewrite the getElements()
function actually return a UIImage
. Of course this will likely have to be an optional, as randomElement()
returns an optional element to handle cases where the array is empty.
func getElements() -> UIImage? {
let elements = ["rectangle", "circle", "triangle"]
guard let randomElement = elements.randomElement() else {
return nil
}
return UIImage(named: randomElement)
}
And then at the point of usage, you can just do something like:
cell.contents = getElements()?.cgImage
2 - Alternatively, you could update your function getElements()
to return a string. This is basically the same, but it moves the logic to test the optional to outside of the getElements()
function.
func getElements() -> String? {
let elements = ["rectangle", "circle", "triangle"]
return elements.randomElement()
}
And then at the point of usage, you have to test the optional, and use it to initialise the image:
if let element = getElements() {
cell.contents = UIImage(named: element)?.cgImage
}
Personally, I prefer option one, as it removes the burden of checking the nil string from the point of usage. But it all depends on what you're trying to achieve. I would also perhaps consider renaming the function to something like randomImage()
, as getElements()
is perhaps a little unclear, but that's just personal preference.
Hope that helps.