0

I already tried this:

var newArray = oldArray.map
    {
        Character($0)
}

where oldArray is an array with type [Any]. However, I get an error when I insert that code. Is there another option?

3
  • What's the error? Commented Nov 2, 2016 at 15:47
  • "Cannot invoke initializer for type 'Character' with an argument list of type ' ((Any))'" Commented Nov 2, 2016 at 15:56
  • What is oldArray an array of? Commented Nov 2, 2016 at 16:31

2 Answers 2

2

Any cannot be directly converted to Character, but needs to first be casted to String (from which it is a simple task to convert (the first character in the string) to Character:

let arr: [Any] = ["k", "n"]
let newArr = arr.flatMap { ($0 as? String)?.characters.first }
print(newArr, type(of: newArr)) // ["k", "n"] Array<Character>
Sign up to request clarification or add additional context in comments.

Comments

0

If oldArray contains object of type Character:

var oldArray:[Any] = []
....
var newArray = oldArray.map {
        $0 as! Character
}

in this way it compiles, but you can get runtime exception accordin to the value stored in oldArray.

5 Comments

This will blow up spectacularly if the elements in oldArray aren't Characters (or can't be converted to Characters). And if they are already Characters, then there's no need for them to be converted.
yes but it compiles, an no error are generated by the compiler. The user had an error at compile time.
Ok, thank you no errors now! However, I wanted to use this code furthermore in my code. This code worked with an other array, but now I get the error: 'Value of type '[Character]' has no member 'character'". This is my line of code: let decoded = String(newArray.characters.map({ decode[$0] ?? $0 })) can you answer this or should I make another thread? Thank you anyway!
Edit: I do get a runtime error when executing this code:Thread 1: signal SIGABRT... lines below are saying this: Could not cast value of type 'Swift.String' (0x1003e4a18) to 'Swift.Character' (0x1003de490). 2016-11-02 17:02:40.567080 test[844:164055] Could not cast value of type 'Swift.String' (0x1003e4a18) to 'Swift.Character' (0x1003de490).
A String cannot be cast to Character. Your treating a String like a Character and you cannot do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.