【问题标题】:Cannot assign value of type '[String]' to type 'String?' (Swift)无法将类型“[String]”的值分配给类型“String?” (迅速)
【发布时间】:2016-05-24 23:02:03
【问题描述】:

在用于 ios 开发的 swift (Xcode) 中,我正在尝试将 UILabel 的文本设置为数组的元素。这是一个简单的项目,当您按下按钮时:在 50 个元素的数组中,50 个元素将被随机化,然后选择 3 个,我希望这 3 个显示在 UILabel 上,但我得到了错误我无法将“[String]”类型的值分配给“String?” (迅速)。这是我的代码主要代码

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var altLabel: UILabel!
    @IBOutlet weak var asianLabel: UILabel!
    @IBOutlet weak var bluesLabel: UILabel!
    @IBOutlet weak var classicalLabel: UILabel!
    @IBOutlet weak var countryLabel: UILabel!
    @IBOutlet weak var danceLabel: UILabel!
    @IBOutlet weak var edmLabel: UILabel!
    @IBOutlet weak var emotionalLabel: UILabel!
    @IBOutlet weak var euroLabel: UILabel!
    @IBOutlet weak var indieLabel: UILabel!
    @IBOutlet weak var inspirationalLabel: UILabel!
    @IBOutlet weak var jazzLabel: UILabel!
    @IBOutlet weak var latinLabel: UILabel!
    @IBOutlet weak var newAgeLabel: UILabel!
    @IBOutlet weak var operaLabel: UILabel!
    @IBOutlet weak var popLabel: UILabel!
    @IBOutlet weak var rbLabel: UILabel!
    @IBOutlet weak var reggaeLabel: UILabel!
    @IBOutlet weak var rockLabel: UILabel!
    @IBOutlet weak var rapLabel: UILabel!

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

    @IBAction func altButton(sender: UIButton) {

        let altSongs: [String] = ["Spirits by The Strumbellas", "Ride by Twenty One Pilots", "Ophelia by The Lumineers", "Dark Necessities by Red Hot Chili Peppers", "Bored to Death by Blink-182", "HandClap by Fitz And Tantrums", "Walking An A Dream by Empire Of The Sun", "Kiss This by The Struts", "Woman Woman by AWOLNATION", "First by Cold War Kids", "Way Down We Go by Kaleo", "Gone by Jr Jr", "Genghis Khan by Miike Snow", "Stressed Out by Twenty One Pilots", "Adventure Of A Lifetime by Coldplay", "2AM by Bear Hands", "Take It From Me by KONGOS", "Soundcheck by Catfish And The Bottlemen", "Brazil by Declan McKenna", "Destruction by Joywave", "Centuries by Fallout Boy", "Castle by Hasley", "First by Cold war Kids", "Unsteady (Erich Lee Gravity Remix) by X Ambadassadors", "Best Day Of My Life by American Authors", "Hymn For The Weekend by Coldplay", "Seven Nation Army by The White Stripes", "This is Gospel by Panic! At The Disco", "Riptide by Vance Joy", "Uma Thurman by Fallout Boy", "My Song Know What You Did In The Dark (Light Em Up) by Fall Out Boy", "Radioactive by Imagine Dragons", "Car Radio by Twenty One Pilots", "Walking On A Dream by Empire Of The Sun", "Viva La Vide by Coldplay", "Left Hand Free by Alt-J", "Tear in My Heart by Twenty One Pilots", "Death Of A Bachelor by Panic! At The Disco", "Demons by Imagine Dragons", "Emperor's New Clothes by Panic! At The Disco", "I Write Sins Not Tradegies by Panic! At The Disco", "Sail by AWOLNATION", "Twice by Catfish And The Bottlemen", "Colors by Hasley", "Nobody Really Cares If You Don't Go To The Party", "Courtney Barnett", "A Sky Full Of Stars", "On Top Of The World by Imagine Dragons", "Woman Woman by AWOLNATION", "Take Me T Church by Hozier"]

        var shuffled = altSongs.shuffle;
        shuffled = altSongs.choose(3)
        altLabel.text = shuffled  //(ending brackets are in place, just not shown here. **Rest of the code is just buttons structured in same format as this one**)

我只是 iOS 开发的初学者

方法代码://(选择)和(随机播放)

import Foundation
import UIKit

extension Array {
    var shuffle: [Element] {
        var elements = self
        for index in indices.dropLast() {
            guard
            case let swapIndex = Int(arc4random_uniform(UInt32(count - index))) + index
                where swapIndex != index else {continue}
            swap(&elements[index], &elements[swapIndex])

        }
        return elements
    }
        mutating func shuffled() {
            for index in indices.dropLast() {
                guard
            case let swapIndex = Int(arc4random_uniform(UInt32(count - index))) + index
                where swapIndex != index
                    else { continue }
                swap(&self[index], &self[swapIndex])
            }
        }
        var chooseOne: Element {
            return self[Int(arc4random_uniform(UInt32(count)))]
        }
        func choose(n: Int) -> [Element] {
            return Array(shuffle.prefix(n))
        }
}

【问题讨论】:

    标签: ios arrays swift uilabel ibaction


    【解决方案1】:

    对于您的错误:“unexpectedly found nil while unwrapping an Optional value”,请查看我关于它们的帖子,了解“!”和 '?'对于 Swift 开发至关重要: What are '!' and '?' marks used for in Swift

    此外,正如其他答案所提到的,您返回的是一个数组值,而不是您应该给出一个 String 值,然后将其分配给您的 label.text 值。为此,您可以尝试以下方法:

    altLabel.text = "\(shuffled[0]), \(shuffled[1]), \(shuffled[2])"
    

    【讨论】:

    • 我看了你的帖子,我明白了,但我不知道在我的代码中我会在哪里放置任何“?”。此外,当我输入该代码时,它给了我一个错误,说我无法将类型“()”分配给类型“字符串?”
    • @RuchirMehta 好的,根据您所说:“这是代码行:altLabel.text = selectedThree[0] + " " + selectedThree[1] + " " + selectedThree[2] " 和 "... 无法将类型 '()' 分配给类型 'String?'",问题是在 "altLabel.text = shuffled" 中使用的 'shuffled' 返回一个 'empty array' 或 'nil '。因此,您在“数组扩展”中的方法中似乎遗漏了一些东西
    • 当我使用代码 "altLabel.text = selectedThree[0] + " " + selectedThree[1] + " " + selectedThree[2]"" 和使用你给我的代码“altLabel.text =”(shuffled[0]),(shuffled[1]),(shuffled[2])“”。我曾经让“type'()'输入'String?' " 运行您的代码时出错,但现在没有错误。(反斜杠在那里;只是没有显示在评论中)
    【解决方案2】:
    var shuffled = altSongs.shuffle; // Line 1
    shuffled = altSongs.choose(3)    // Line 2
    altLabel.text = shuffled         // Line 3
    

    将上面的代码替换为

    let shuffled = altSongs.shuffle;
    let selectedThree = shuffled.choose(3)
    altLabel.text = selectedThree[0] + " " + selectedThree[1] + " " + selectedThree[2]
    

    在这里,您将数组打乱并放入shuffled,然后在selectedThree 中选择前三个元素的数组。

    selectedThree 是一个字符串数组。我们可以迭代数组以获取字符串,也可以只使用前三个元素。

    【讨论】:

    • 我仍然得到同样的错误(不能将类型 '[String]' 分配给类型 'String?' 进行更正时
    • 在您的问题中添加实现“shuffle”和“choose”方法的代码。
    • 现在我遇到了致命错误:在展开可选值时意外发现 nil
    • 我输入了该代码,但仍然遇到同样的致命错误。我什至尝试按照其他有关致命错误的帖子中的建议重新创建连接,但没有任何效果。
    • @RuchirMehta 我已经尝试并测试过了。应该没有问题。尝试清理您的项目。请交叉检查此 ViewController 中的代码dropbox.com/s/xht4wjhabrmzvl8/ViewController.swift?dl=0
    【解决方案3】:

    我不知道你在哪里定义了shufflechoose,我认为你错误地实现了它们。

    我认为您可以创建一个返回字符串数组的choose 扩展方法:

    func chooseFromArray<T>(array: [T], amountToChoose: Int) -> [T] {
        var returnVal: [T] = []
        var arrayCopy = array
        for _ in 0..<amountToChoose {
            let chosen = Int(arc4random_uniform(UInt32(arrayCopy.count)))
            returnVal.append(arrayCopy[chosen])
            arrayCopy.removeAtIndex(chosen)
        }
        return returnVal
    }
    

    然后你可以这样称呼它:

    var chosenSongs = chooseFromArray(altSongs, amountToChoose: 3)
    

    你说你想在标签中显示一个数组。所以我猜你想这样做?

    altLabel.text = chosenSongs.joinWithSeparator(", ")
    

    我认为应该可以解决它。

    【讨论】:

    • 所以是的,就像在其他 cmets 中看到的那样,我仍然遇到这个致命错误:在展开可选值时意外发现 nil
    • @RuchirMehta 在您的代码中的某处,您将“nil”值传递给“var”,您已使用“!”对其进行了定义,这可能就是您收到此错误的原因。跨度>
    • @RuchirMehta 我认为该错误是由您在此问题中未显示的代码的其他部分引起的。我建议您找出错误确切发生的位置。然后,您可以就错误提出一个新问题。记得告诉我们您尝试解决的问题!之后,您可以接受此问题的其中一个答案。
    • @Burak 唯一的“!”我使用的是 UILabel 网点和选择和随机播放的方法,例如:“where swapIndex != index”
    • @sweeper 我如何确定错误的确切位置? Xcode 向我显示的所有内容都是它停止工作的代码行上的一个红色断点。
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多