gpt4 book ai didi

来自字符串的 Swift startIndex

转载 作者:行者123 更新时间:2023-11-28 10:19:37 25 4
gpt4 key购买 nike

我的代码中有一个奇怪的错误。我正在用 Swift 构建一个 iOS 应用程序。该代码包含以下功能:

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 _ {
}
}

在特定部分:

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

它给我一个错误,我之前尝试添加一个断点,并尝试打印“string”,这返回了我的字符串。之后我尝试了 string[string.startIndex] == "•",它返回了 true。但是现在,如果我运行代码并尝试打开运行此代码的页面,我会收到以下错误:

fatal error :无法从空字符串形成字符

关于如何解决这个问题的任何想法?字符串似乎不是空的...

谢谢!

最佳答案

如果您有一个空字符串,您将看到该错误。如果您首先进行测试以确保字符串不为空,那么您应该没问题。

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

关于来自字符串的 Swift startIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36727034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com