簡體   English   中英

無法將類型“ [String]”的值分配給類型“ String?” (迅速)

[英]Cannot assign value of type '[String]' to type 'String?' (Swift)

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

對於您的錯誤:“ unexpectedly found nil while unwrapping an Optional value ”,看看我關於它們的帖子,理解為'!' 和'?' 對於Swift開發至關重要: 什么是“!” 和'?' Swift中使用的標記

另外,正如還提到的其他答案一樣,您將返回一個數組值,而應該提供一個String值,然后將其分配給您的label.text值。 為此,您可以嘗試以下操作:

altLabel.text = "\(shuffled[0]), \(shuffled[1]), \(shuffled[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並將其放入shuffled然后在selectedThreeselectedThree前三個元素的數組。

selectedThree是字符串數組。 我們可以迭代數組以獲取字符串,也可以僅使用前三個元素。

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

我認為應該修復它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM