简体   繁体   English

无法将类型“ [String]”的值分配给类型“ String?” (迅速)

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

in swift (Xcode) for ios development, I'm trying to set my UILabel's text to the elements of an array. 在iOS开发的Swift(Xcode)中,我试图将UILabel的文本设置为数组的元素。 This is for a simple project where when you press a button: out of a array for 50 elements, the 50 elements will be randomized and then 3 will be chosen and i want those 3 to be displayed on the UILabel, but I get the error that I cannot assign value of type '[String]' to type 'String?' 这是一个简单的项目,在您按下按钮时:从50个元素的数组中随机取出50个元素,然后选择3个元素,我希望将这3个元素显示在UILabel上,但出现错误我无法将类型“ [String]”的值分配给类型“ String?” (Swift). (迅速)。 Here is my code main code 这是我的代码主要代码

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**)

I'm only a beginner at iOS developing 我只是iOS开发的初学者

Code for the methods : //(choose) and (shuffle) 方法代码 ://(选择)和(随机播放)

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

For your error: " unexpectedly found nil while unwrapping an Optional value ", have a look at my post about them, understanding '!' 对于您的错误:“ unexpectedly found nil while unwrapping an Optional value ”,看看我关于它们的帖子,理解为'!' and '?' 和'?' is crucial for Swift development: What are '!' 对于Swift开发至关重要: 什么是“!” and '?' 和'?' marks used for in Swift Swift中使用的标记

Also, as other answers mentioned also, you are returning an array value instead you should give a String value and then assign it to your label.text value. 另外,正如还提到的其他答案一样,您将返回一个数组值,而应该提供一个String值,然后将其分配给您的label.text值。 For this, you can try below: 为此,您可以尝试以下操作:

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

Replace the above code with 将上面的代码替换为

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

Here you shuffle the array and put it in shuffled then pick array of first three elements in selectedThree . 在这里,您可以对数组进行shuffled并将其放入shuffled然后在selectedThreeselectedThree前三个元素的数组。

selectedThree is an array of strings. selectedThree是字符串数组。 We can either iterate the array to get the string or just use the first three elements. 我们可以迭代数组以获取字符串,也可以仅使用前三个元素。

I don't know where did you define shuffle and choose and I think you implemented them incorrectly. 我不知道您在哪里定义shufflechoose ,我认为您没有正确实现它们。

I think you can just create a choose extension method that returns an array of strings: 我认为您可以创建一个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
}

And then you can just call it like this: 然后您可以这样称呼它:

var chosenSongs = chooseFromArray(altSongs, amountToChoose: 3)

You said you want to display an array in a label. 您说过要在标签中显示数组。 So I guess you want to do it like this? 所以我想你想这样做吗?

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

I think that should fix it. 我认为应该修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift不能指定类型'()'的值来键入'String?' - Swift cannot assign value of type '()' to type 'String?' 无法将类型“ [String]”的值分配为类型“ String”? 迅捷2 - Cannot assign value of type '[String]' to type 'String? Swift 2 错误:无法将类型“[String]”的值分配给 swift 中的“String”类型 - Error: Cannot assign value of type '[String]' to type 'String' in swift 无法将类型“ [String]”的值分配给类型“ [MovieVO]”的值-Swift - Cannot assign a value of type '[String]' to a value of type '[MovieVO]' - Swift 无法将String类型的值分配为AnyObject类型? 斯威夫特3.0 - Cannot assign value of type String to type AnyObject? Swift 3.0 无法分配类型“[ResultItem]?”的值键入“字符串?” Swift 5 - Cannot assign value of type '[ResultItem]?' to type 'String?' Swift 5 不能快速分配“ String”类型的值来输入“ UILabel” - Cannot assign a value of type “String” to type “UILabel” in swift 无法将类型“ [String]”的值分配给类型“ String?” - Cannot assign value of type '[String]' to type 'String?' 无法将类型[[(string,string)]&#39;的值分配给类型[[string:string]&#39; - cannot assign value of type '[(string, string)]' to type '[string : string]' 无法将String类型的值分配为UITextField类型 - Cannot assign a value of type String to type UITextField
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM