Reputation: 9120
I'm extracting a number out of string of numbers in a character but unable either to convert that character to string or to int. Here is my code:
func processString(_ s: String) ->Bool {
var sum = 0
for char in s{
let number = String(char){ //error Cannot invoke initializer for type 'String' with an argument list of type '(Character, () -> ())'
}
}
}
if I try to converted to Int:
func processString(_ s: String) ->Bool {
var sum = 0
for char in s{
let number = Int(String(char)){ //Cannot invoke initializer for type 'Int' with an argument list of type '(String, () -> ())'
}
}
}
Any of you knows what I'm doing wrong or why can not convert the character to string or int?
I'll really appreciate your help.
Upvotes: 1
Views: 239
Reputation: 2718
You have some extra { }
brackets in there that are not necessary. Removing those should solve the compiler issues.
func processString(_ s: String) ->Bool {
var sum = 0
for char in s{
let charString = String(char)
print(charString)
}
}
On this next example, since the Int(_ string: String) initializer can return nil, you could use an if let
statement to unwrap the result, which looks like what you may be trying to do with the { }
It would look like this:
func processString(_ s: String) ->Bool {
var sum = 0
for char in s{
if let number = Int(String(char)) {
// number is not nil
}
}
}
Upvotes: 1