gpt4 book ai didi

ios - NSAttributedString 缺少返回值

转载 作者:行者123 更新时间:2023-11-28 10:30:23 26 4
gpt4 key购买 nike

我试图将 VC 中的这个函数变成扩展中的函数(因为我需要在多个 VC 中访问它,所以我试图返回 attributedStringWithRtf 以便我可以在别处使用它。

func populateTextViewWithCurrentScene() {

let fileURL = getFileURL()

do {
let attributedStringWithRtf:NSAttributedString = try NSAttributedString(
url: fileURL,
options: [.documentType: NSAttributedString.DocumentType.rtf],
documentAttributes: nil
)
self.textViewOutlet.attributedText = attributedStringWithRtf
}
catch {
print("failed to populate text view with current scene with error: \(error)")

}

}

到目前为止,我已经按照此处的指南进行了尝试 How could I create a function with a completion handler in Swift?而且我还尝试了一个在函数之前声明 var 的版本。我在下面遇到的错误是 Cannot call value of non-function type 'NSAttributedString'。

我知道有很多关于这类事情的问题,但很多都是针对旧版本的 Swift

func populateTextViewWithCurrentScene(rtfString: NSAttributedString) -> Void {

let fileURL = getFileURL()
do {
let rtfString:NSAttributedString = try NSAttributedString(
url: fileURL,
options: [.documentType: NSAttributedString.DocumentType.rtf],
documentAttributes: nil
)
}
catch {
print("failed to populate text view with current scene with error: \(error)")
}
rtfString()
}

最佳答案

我继续创建了 UIViewControllerextension,它应该提供您正在寻找的内容。每行都包含注释以解释我所做的决定。

如果某些部分不清楚或未按预期工作,请随时发表评论。

import UIKit

// You mentioned wanting to extend your viewcontroller
// so I extend UIViewController to support that
extension UIViewController {
// Returns an optional NSAttributedString, based upon successfully loading the file contents
func loadString() -> NSAttributedString? {
do {
// Everything is cleaned up into a single return command,
// including the getFileURL, which can be used as a parameter instead
// of creating a variable for it
return try NSAttributedString(url: getFileURL(),
options: [.documentType: NSAttributedString.DocumentType.rtf],
documentAttributes: nil)
} catch {
// If this fails, use your existing print command
print("failed to populate text view with current scene with error: \(error)")
// and then return nil to indicate that nothing was loaded
return nil
}
}
}

这是根据您和 rmaddy 的以下评论构建的。

正如我最初评论中提到的,解决方案不是合并 try & return,而是简化代码。

你可以这样看函数:

"I want to try and open a file that is located at getFileURL(), and would like to use some options I specify with my options: parameter. Since this action can fail, Xcode makes me use try. Assuming that this file is successfully opened, then return the contents back to the caller in the form of an NSAttributedString. However, if this fails, print out a message telling me why it failed and then return a nil to indicate that no data is returned."

关于ios - NSAttributedString 缺少返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56447368/

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