I am trying to convert typescript to Swift.
I am currently working on using stringinput, in this case the initials of a user, to a set color. In our Frontend application, the following javascript code is used:
export default function getColorFromString(value: string) {
var hash = 0;
if (value.length === 0) return hash;
for (var i = 0; i < value.length; i++) {
hash = value.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash;
}
hash = ((hash % this.colors.length) + this.colors.length) % this.colors.length;
return this.colors[hash];
}
this.colors
is defined as:
const colors = [
'#e51c23',
'#e91e63',
'#9c27b0',
'#673ab7',
'#3f51b5',
'#5677fc',
'#03a9f4',
'#00bcd4',
'#009688',
'#259b24',
'#8bc34a',
'#afb42b',
'#ff9800',
'#ff5722',
'#795548',
'#607d8b',
];
I am having some difficulty with porting this code to Swift. I have tried to port it, but I am struggling with compilation errors.
This is my attempt so far. Keep in mind, this doesn't compile; it just shows that I have made an attempt myself.
func getColorFromString(value: String) -> String {
var hash = 0
for (index, value) in value.enumerated() {
hash = UnicodeScalar(value[index]) + ((hash << 5) - hash);
hash = hash & hash;
}
}
Could anyone help me convert this to swift?
Update: this question was closed because of similarities with How to use hex color values, but this does not answer my question. Because I am looking for information on how to convert a string to hash to a specific array index. This array index contains the actual hex values. At some point these hex values need to be converted to color and only at that point, the related questions will be useful.