This is my function in objc:
+ (NSString *)hexForString:(NSString *)string{
NSUInteger charIndex = 0;
for (NSUInteger i = 0; i < string.length; i++){
charIndex += (NSUInteger )[string characterAtIndex:i];
}
NSArray *colors = @[
@"1abc9c", @"2ecc71", @"3498db",
@"9b59b6", @"34495e", @"16a085",
@"27ae60", @"2980b9", @"8e44ad",
@"2c3e50", @"f1c40f", @"e67e22",
@"e74c3c", @"95a5a6", @"f39c12",
@"d35400", @"c0392b", @"bdc3c7",
@"7f8c8d"
];
charIndex %= colors.count;
NSLog(@">>po modulo %lld", charIndex); // output is 13 for "Johny ivan"
return colors[charIndex];
}
and now Swift:
func hex(for string: String) -> String {
var index = 0
string.forEach { character in
index += character.wholeNumberValue ?? 0
}
let colors = [
"1abc9c", "2ecc71", "3498db",
"9b59b6", "34495e", "16a085",
"27ae60", "2980b9", "8e44ad",
"2c3e50", "f1c40f", "e67e22",
"e74c3c", "95a5a6", "f39c12",
"d35400", "c0392b", "bdc3c7",
"7f8c8d",
]
index %= colors.count
print("+++ \(index)") // output is 0 for "Johny ivan"
return colors[index]
}