我遇到过这个问题几次,我试图将函数从一个 swift 文件传递到另一个文件,然后收到错误“在范围内找不到 '_'”。我想知道为什么会发生这种情况以及如何解决它?我尝试创建一个公共函数 public func fetchJokesAPI() ,同时将该函数的类设为 Observable 对象,以便我能够在我的 swift 文件中传递该函数。为什么编译器在作用域中找不到我的函数?下面是一些代码,可以进一步参考该问题。
//Model
import Foundation
struct DecodingError: Error{}
struct JokesModel: Codable {
let type: String
let value: Value
}
// MARK: - Value
struct Value: Codable {
let id: Int
let joke: String
}
class JokesAPI {
var session: URLSession?
// MARK: Getting random jokes from API endpoint
func fetchJokes() {
guard let url = URL(string: "https://api.icndb.com/jokes/random/") else {
print("Cannot generate URL")
return
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print(error.localizedDescription)
return
}
guard (response as? HTTPURLResponse) != nil else {
print("No Response")
return
}
struct JokesResponse: Decodable {
let data: [JokesModel]
}
guard let data = data, let dataString = String(data: data, encoding: .utf8)
else {
print("No Data")
return
}
do {
let jokeResponse = try JSONDecoder().decode(JokesResponse.self, from: data)
print(jokeResponse.data)
} catch {
print("Error decoding joke response:", error)
}
}
task.resume()
}
}
// Another Swift File that is a Coco touch file.
import UIKit
import Foundation
class HomeViewController: UIViewController {
private let service = JokesAPI()
private var joke: [JokesModel]?
@IBOutlet var tellAeAJokeButton: UIButton!
@IBOutlet var jokeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
service.fetchJokes()
}
@IBAction func didPressBtn() {
// MARK: Actions for both fetching a joke from the API, & Text-Speech using AI Voice
service.fetchJokes()
joke = [JokesModel]()
jokeLabel.text = JokesModel().joke
// Value of type 'JokesModel' has no member 'joke'
// Missing argument for parameter 'from' in call
您收到错误是因为您需要类的实例来调用函数。
为了让你的代码工作,你可以做这样的事情,你的 viewController 接受一个服务
JokesWebService
像这样,更好的选择是在 viewModel 上使用该服务,如果你已经有一个服务,但如果没有的话,这应该可以解决问题让您开始:
import UIKit
class HomeViewController: UIViewController {
@IBOutlet var tellAeAJokeButton: UIButton!
private var service: JokesWebService!
override func viewDidLoad() {
super.viewDidLoad()
service = JokesWebService()
}
@IBAction func didPressBtn() {
service.fetchJokesAPI()
}
}