2

I am trying to get the contents of a string:

var oldString = "hi this \t is my \t string"
oldString = String(oldString.componentsSeparatedByString("\t"))
print(oldString[1])

I get the ERROR : " 'subscript' is unavailable:cannot subscript String with an Int..."

How would I access a string that is contained in another string? The only way I have come up with is to get character by character using:

for index in content.characters.indices{
    print(String(oldString[index]))
}

The code above results in:

h,
i,
t,
h,
..

I need:

hi this,
is my,
string

Thank you in advance!

0

3 Answers 3

1

You should read the error message and figure out where does the error message come from.

Your String(oldString.componentsSeparatedByString("\t")) gives you a String not [String].

What you need to do is assigning oldString.componentsSeparatedByString("\t") to an array:

let stringArray = oldString.componentsSeparatedByString("\t")
for str in stringArray {
  print(str)
}
Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense. How would I make it a [String]?
oldString.componentsSeparatedByString("\t") returns a [String]. You are taking the result of that and making a new String from it, which is not what you want to do.
1

In swift you can extend any type and add overloads for different operations. In the example below we've created an extension that allows you to subscript String returning each word and get an array from your string.

Simply paste this into a playground to test:

extension String {
    
    func array() -> [String] {
        return self.componentsSeparatedByString("\t")
    }
    
    subscript (i: Int) -> String {
        return self.componentsSeparatedByString("\t")[i]
    }
}

Once you've added your extension, you can use it throughout your application like so:

var str = "hi this \t is my \t string"

print(str[0]) //prints hi this

for i in str.array() {
    print(i)
}

prints:

hi this

is my

string

Comments

0
    var oldString = "hi this \t is my \t string"
    let stringArray = oldString.componentsSeparatedByString("\t")

    //In case you also need the index while iterating
    for (index, value) in stringArray.enumerate(){
        print("index is \(index) and string is \(value)")
    }

    for str in stringArray{
        print(str)
    }

Output will be as follows
index is 0 and string is hi this 
index is 1 and string is  is my 
index is 2 and string is  string

hi this 
 is my 
 string

Comments

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.