1

I tried to converting a string into an array, but its showing error

var boolean = "01101010101001010111"

i tried to spilt the string by characters it didn't worked and tried to convert it into array.

resultArray = [0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,1,0,1,1,1]

My code attempt

boolean = "01101010101001010111"
let componentsArray =  boolean.components(separatedBy: .controlCharacters) 

resultArray = Array(componentsArray) as! [Int]

And the error

Error: Generic parameter "Element could not be inferred"

3
  • What did you try and what error did you get? What result do you expect for the string "0-X/1Y€🤡"? Commented Jan 24, 2017 at 6:42
  • updated with error @MartinR Commented Jan 24, 2017 at 6:45
  • @Joe let resultArray = boolean.characters.flatMap{Int(String($0))} Commented Jan 24, 2017 at 6:47

1 Answer 1

4

A possible solution (now updated for Swift 4 and later):

let zeroOneString = "01101010101001010111"

let resultArray = zeroOneString.compactMap { char in
    char == "0" ? 0 : char == "1" ? 1 : nil
}

print(resultArray) // [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1]

zeroOneString.compactMap maps the sequences of all characters in the string. The closure maps "0" to 0 and "1" to 1. Everything else is mapped to nil and ignored by compactMap.

Sign up to request clarification or add additional context in comments.

1 Comment

Swift 5 Update: let array = str.compactMap { $0 == "0" ? 0 : 1}

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.