You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5报错:无法将'[ResultItem]?'赋值给'String?'及随机名言实现求助

解决iOS名言随机显示的错误问题

问题根源

你遇到的错误有两个核心原因:

  1. JSON格式不合法:原JSON文件存在重复的quote键,JSON对象不允许重复键,导致解析逻辑完全失效。
  2. 代码类型不匹配:你试图将数组类型[ResultItem]?直接赋值给UITextView的text属性(要求String?),同时解析后的全局变量未正确赋值。

步骤1:修正JSON文件格式

将原JSON改为符合规范的数组结构,匹配你定义的Result和ResultItem结构:

{
  "data": [
    {"quote": "The greatest glory in living lies not in never falling, but in rising every time we fall. -Nelson Mandela"},
    {"quote": "The way to get started is to quit talking and begin doing. -Walt Disney"},
    {"quote": "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough. -Oprah Winfrey"},
    {"quote": "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success. -James Cameron"},
    {"quote": "Life is what happens when you're busy making other plans. -John Lennon"},
    {"quote": "Spread love everywhere you go. Let no one ever come to you without leaving happier. -Mother Teresa"},
    {"quote": "Don't judge each day by the harvest you reap but by the seeds that you plant. -Robert Louis Stevenson"},
    {"quote": "Tell me and I forget. Teach me and I remember. Involve me and I learn. -Benjamin Franklin"},
    {"quote": "The future belongs to those who believe in the beauty of their dreams. -Eleanor Roosevelt"},
    {"quote": "If life were predictable it would cease to be life and be without flavor. -Eleanor Roosevelt"},
    {"quote": "Life is a succession of lessons which must be lived to be understood. -Ralph Waldo Emerson"},
    {"quote": "You will face many defeats in life, but never let yourself be defeated. -Maya Angelou"},
    {"quote": "The only impossible journey is the one you never begin. -Tony Robbins"},
    {"quote": "Only a life lived for others is a life worthwhile. -Albert Einstein"},
    {"quote": "Life is really simple, but we insist on making it complicated. -Confucius"},
    {"quote": "Life is a long lesson in humility. -James M. Barrie"},
    {"quote": "Love the life you live. Live the life you love. -Bob Marley"},
    {"quote": "Many of life's failures are people who did not realize how close they were to success when they gave up. -Thomas A. Edison"},
    {"quote": "Life is made of ever so many partings welded together. -Charles Dickens"}
  ]
}

步骤2:修改ViewController代码

修复变量赋值、类型匹配问题,实现随机名言功能:

class ViewController: UIViewController {
    
    @IBOutlet weak var quoteView: UITextView!
    
    var result: Result?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        quoteView.text = "You only live once, but if you do it right, once is enough. — Mae West"
        parsejson()
    }
    
    @IBAction func quoteTriggered(_ sender: Any) {
        // 提取所有非空名言并随机选取
        guard let quotes = result?.data.compactMap({ $0.quote }), !quotes.isEmpty else {
            quoteView.text = "No quotes available"
            return
        }
        let randomIndex = Int.random(in: 0..<quotes.count)
        quoteView.text = quotes[randomIndex]
    }
    
    private func parsejson() {
        guard let path = Bundle.main.path(forResource: "data", ofType: "json") else {
            print("找不到JSON文件")
            return
        }
        
        let url = URL(fileURLWithPath: path)
        
        do {
            let jsonData = try Data(contentsOf: url)
            self.result = try JSONDecoder().decode(Result.self, from: jsonData)
            print("JSON解析成功")
        } catch {
            print("解析错误: \(error.localizedDescription)")
        }
    }
}

struct Result: Codable {
    let data: [ResultItem]
}

struct ResultItem: Codable {
    let quote: String
}

关键修改说明

  1. JSON解析修正:将局部变量result赋值给全局的self.result,确保解析后的数据能被按钮事件调用。
  2. 类型匹配修复:通过compactMap过滤空名言,生成字符串数组后随机选取元素,赋值给quoteView.text。
  3. 稳定性提升:去掉强制解包的try!,改用try并捕获错误,避免因JSON格式问题导致崩溃。

内容的提问来源于stack exchange,提问作者Razvan Constantin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:51:33