无法指定类型'[String]'的值来键入'String?' (迅速)

时间:2016-05-24 05:03:34

标签: ios arrays swift uilabel ibaction

在用于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))
        }
}

3 个答案:

答案 0 :(得分:2)

对于您的错误:“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])"

答案 1 :(得分:1)

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是一个字符串数组。我们可以迭代数组来获取字符串,或者只使用前三个元素。

答案 2 :(得分:0)

我不知道您在哪里定义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(", ")

我认为应该解决它。