Wenjie Zhong
Wenjie Zhong

Reputation: 33

Convert [String]? to String in Swift

For my project, I extracted tweets from a CSV file in Swift. Problem is now all tweets are parsed as one element in an array, separated by ",".

let tweetsOfColumns = columns["tweet"]
let seperatedColumns = tweetsOfColumns.componentsSeparatedByString(",")

Error message: '[String]?' does not have a member named 'componentsSeparatedByString'.

I checked if tweetsOfColumns contains multiple elements, but it doesn't allow me to subscript with tweetsOfColumns[index].

Upvotes: 0

Views: 12645

Answers (5)

David Berry
David Berry

Reputation: 41226

Looking at the link you reference, columns["tweets"] is going to give you back an array of the values from the "tweets" column, so it's what you need already, there's no additional comma's to split things on, you just need:

let seperatedColumns = columns["tweet"]

to have an array containing the tweet column for each row.

Upvotes: 1

Price Ringo
Price Ringo

Reputation: 3440

Based on David's question and the OP's response in the OP comments, you can use map on the Array returned by columns["tweet"]. Please post actual data/code in the future.

let columns = [
    "tweet":["handleX,tag1,tag2,textA,textB",
             "handleY,tag1,tag2,textC,textD"]]

var chunk = [[String]]()
if columns["tweet"] != nil {
    chunk = columns["tweet"]!.map {
        return $0.componentsSeparatedByString(",")
    }
}

enter image description here

Upvotes: 0

Simon
Simon

Reputation: 1076

The problem is probably that you'll get an optional back, which you have to unwrap. And the easiest and most elegant is to use the if-let unwrapper.

if let tweetsOfColumns = columns["tweet"] {
    let seperatedColumns = tweetsOfColumns.componentsSeparatedByString(",")
    // do something with the seperatedColumns
}

Upvotes: 0

Christian
Christian

Reputation: 22343

You have to either use the optional ? to access the string:

let seperatedColumns = tweetsOfColumns?.componentsSeparatedByString(",")

But you should unwrap it:

if let unwrappedTweets = tweetsOfColumns?.componentsSeparatedByString(","){
    let seperatedColumns = unwrappedTweets
}

Upvotes: 0

Dániel Nagy
Dániel Nagy

Reputation: 12015

When you try to get an element from a dictionary, like

columns["tweet"]

it will give you back an optional, because if there is nothing associated with the key, it gives you back nil (None), otherwise the value wrapped in an optional (Some(data)). So you have to unwrap the optional for example:

columns["tweet"]!

Upvotes: 1

Related Questions