create a method that takes string as name parameter and returns a number of it in swift

Here's a simple function that takes a string as the name parameter and returns its ASCII value as a number:

main.swift
func stringToNumber(name: String) -> Int {
    var num = 0
    for char in name.unicodeScalars {
        num += Int(char.value)
    }
    return num
}
151 chars
8 lines

This method works by iterating through each character in the string and adding its ASCII value to a running total. Finally, the total is returned as the result.

Here's an example usage of this function:

main.swift
let myName = "John"
let myNumber = stringToNumber(name: myName) // returns 433
79 chars
3 lines

gistlibby LogSnag