SwiftUI 文本视图:当可选字符串为 nil 时,预期的默认值不起作用

时间:2021-03-21 20:10:25

标签: json swiftui null default optional

无法弄清楚为什么当变量为零时代码不会显示默认值。这是下面的上下文。任何指针将不胜感激。

谢谢!

来自 JSON API 的数据示例: 注意:image_url 只是基本名称,而不是完整路径或文件扩展名。

    [
        {
        "id": 1,
        "title": "Autumn in New York",
        "image_url": ""
        }
    ]

数据模型:

import Foundation

struct Challenge: Codable, Hashable, Identifiable {
  let id: Int
  let title: String
  let imageURL: String?

  private enum CodingKeys: String, CodingKey {
    case id
    case title
    case imageURL = "image_url"
  }
}

查看和查看模型的代码:

import SwiftUI

struct JSONChallengeV2: View {
    @State private var challenge: [Challenge] = []
    
    var body: some View {
        
        ScrollView {

        VStack(alignment: .leading, spacing: 5) {

            ScrollView(.horizontal, showsIndicators: true) {
                
                HStack() {
                        
                    ForEach (challenge) { challenge in

                            NavigationLink(
                                destination:
                                    PlayerView(),
                                label: {
                                    // PROBLEMS OCCUR IN THIS VIEW (see view code below)
                                    JSONChallengeRowView(challenge: challenge)
                            })
                        }
                    }        
                }
            }
            .onAppear {
                getData()
                }
            }
        }
        
    func getData() {
        let url = URL(string: "https://example.com/jsonapi") // EXAMPLE ONLY
        
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            guard error == nil else {
                print(error?.localizedDescription ?? "")
                return
            }
            
            guard data != nil else {
                print("No data")
                return
            }
            
            let decoder = JSONDecoder()
            
            do {
                let loaded = try decoder.decode([Challenge].self, from: data!)
                challenge = loaded
            } catch {
                print("Can't decode data")
            }
        }.resume()
    }
}

子视图代码(上面视图中引用了“JSONChallengeRowView”):

import SwiftUI

struct JSONChallengeRowView: View {

    var challenge: Challenge
    
    var body: some View {

        let thumbnailPrefix = "https://example.com/" // EXAMPLE ONLY
        let thumbnailSuffix = "-001.jpg"

        VStack(alignment: .leading) {
                
// WORKS: Hardcoding a known image base (i.e., "autumn-default":
            RemoteImageView(url: ("\(thumbnailPrefix)\(String(describing: "autumn-default"))\(thumbnailSuffix)"))
                .scaledToFit()
                .cornerRadius(10)
            
            Link("Go", destination: (URL(string: "\(thumbnailPrefix)\("autumn-default")\(thumbnailSuffix)") ?? URL(string: "https://google.com"))!)

// DOESN'T WORK: build succeeds but no default image appears when no "imageURL" value can be found:
            RemoteImageView(url: ("\(thumbnailPrefix)\(String(describing: challenge.imageURL ?? "autumn-default" ))\(thumbnailSuffix)"))
                .scaledToFit()
                .cornerRadius(10)

            Link("Go", destination: URL(string: "\(thumbnailPrefix)\(String(describing: challenge.imageURL ?? "autumn-default"))\(thumbnailSuffix)")!)


// AND WHILE THESE WORK:

            Text("\(challenge.title)")
            Text(challenge.title)

// THESE SIMILARLY DISPLAY NOTHING (despite values in the "title" variable, used as a default value here for testing only):

            Text("\(challenge.imageURL ?? challenge.title)")
            Text(challenge.imageURL ?? challenge.title)

        }
    }
}

1 个答案:

答案 0 :(得分:0)

Nick 关于 image_url 包含一个空字符串而不是 nil 的观点为我指明了正确的方向,并且根据我在其他地方的 Swift 学习者论坛的提示,我使用此修改来修复不起作用的部分:

challenge.imageURL.isEmpty ? "autumn-default" : "\(challenge.imageURL)"

例如,这里:

RemoteImageView(url: "\(thumbnailPrefix)" + (challenge.imageURL.isEmpty ? "autumn-default" : "\(challenge.imageURL)") + "\(thumbnailInfix)" + (challenge.imageURL.isEmpty ? "autumn-default" : "\(challenge.imageURL)") + "\(thumbnailSuffix)")

我也成功地将此语法应用于链接和文本视图。

再次感谢大家!

相关问题