swift 无法在属性初始值设定项内使用示例成员“searchQuery”;属性初始值设定项在“self”可用之前运行

t0ybt7op  于 2023-06-28  发布在  Swift
关注(0)|答案(1)|浏览(149)

SwiftUI编码较新,似乎无法弄清楚整个初始化器的事情。当我把一个变量放到我的API调用中时,我一直得到这个错误。我试图让TextField的值成为API调用的术语。这是使用CatalogueRequest访问MusicKit。当您手动向请求中输入名称而不是任何变量时,它可以工作。任何帮助将不胜感激!

import SwiftUI 
import MusicKit

struct SearchView: View {
    @State var songs = [songInfo]()
    @State var searchQuery = ""
var body: some View {
    VStack {
        TextField("Search", text: $searchQuery,
    onCommit: {
fetchMusic()
        })
            .padding()
        NavigationView {
            List(songs) { song in
                HStack {
                    AsyncImage(url: song.imageURL)
                        .frame(width: 75, height: 75,     alignment: .center)
                    VStack(alignment: .leading) {
                        Text(song.name)
                            .font(.title3)
                        Text(song.artist)
                            .font(.footnote)
                    }
                    .padding()
                }
                
            }
        }
        .onAppear {
            fetchMusic()
    }
    }
}

private let request: MusicCatalogSearchRequest = {
    var request = MusicCatalogSearchRequest(term: "Cruel     Summer", types: [Song.self])
    request.limit = 25
    return request
}()

private func fetchMusic() {
    Task {
        //Request permission
        let status = await MusicAuthorization.request()
        switch status {
        case .authorized:
            do {
                let result = try await     request.response()
                self.songs = result.songs.compactMap({
                    return .init(name: $0.title,
                                 artist: $0.artistName,
                                 artworkColor:     $0.artwork?.backgroundColor,
                                 imageURL:     $0.artwork?.url(width: 75, height: 75),
                                 imageURLSmall:     $0.artwork?.url(width: 256, height: 256),
                                 imageURLLarge:     $0.artwork?.url(width: 1028, height: 1028))
                })
                print(String(describing: songs[0]))
            } catch {
                print(String(describing: error))
            }
        default: break
            
        }
    }
}
}

#Preview {
    SearchView()
}

我尝试过手动初始化,显式地将其定义为字符串,并不断得到越来越多的错误。

k5ifujac

k5ifujac1#

我看不到request属性在fetchMusic函数之外的任何地方被使用,所以我将它作为该函数内部的局部变量。

private func fetchMusic() {
    Task {
        //Request permission
        let status = await MusicAuthorization.request()
        switch status {
        case .authorized:
            var request = MusicCatalogSearchRequest(term: searchQuery, types: [Song.self])
            request.limit = 25
            do {
                //... rest of code

相关问题