Matthijs Otterloo Matthijs Otterloo - 7 months ago 133
Swift Question

Swift startIndex from string

I'm having a weird bug in my code. I'm building an iOS app in Swift.
The code contains the following function:

func generateAttrString(path: String?) {
do {
let content = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
let array = content.componentsSeparatedByString("\n¶")
let attrStyle = NSMutableParagraphStyle()
attrStyle.lineSpacing = 8
attrStyle.paragraphSpacing = 12

for element in array {
var string = element
var attributes = [
NSParagraphStyleAttributeName: attrStyle,
NSFontAttributeName: UIFont(name: "MyriadPro-Light", size: 17.0)!
]

var attrString = NSMutableAttributedString(string: string, attributes: attributes)
if string[string.startIndex] == "•" {
string.removeAtIndex(string.startIndex)
attributes[NSFontAttributeName] = UIFont(name: "MyriadPro-Regular", size: 17.0)!

let newAttrStyle = attrStyle.mutableCopy() as! NSMutableParagraphStyle
newAttrStyle.paragraphSpacing = 3
newAttrStyle.lineSpacing = 0
attributes[NSParagraphStyleAttributeName] = newAttrStyle

attrString = NSMutableAttributedString(string: string, attributes: attributes)
}


contentArray.append((false, attrString))
}

} catch _ {
}
}


at the specific part of:

if string[string.startIndex] == "•" {


it is giving me an error, I tried adding a breakpoint before, and tried printing "string", this returned me the string. After that I tried string[string.startIndex] == "•", it returned true. But now if I run the code and try opening the page where this code runs I get the following error:

fatal error: Can't form a Character from an empty String

Any idea on how to solve this? The string don't seems to be empty...

Thanks!

Answer

If you have an empty string you'll see that error. If you test first to make sure the string isn't empty you should be okay.

if !string.isEmpty && string[string.startIndex] == "•"  {
Comments