2016-05-24 169 views
0

在Swift(Xcode)for ios開發中,我試圖將我的UILabel的文本設置爲數組的元素。這是一個簡單的項目,當你按下一個按鈕時:50個元素之外的50個元素將被隨機化,然後選擇3個,我希望這3個元素被顯示在UILabel上,但是我得到錯誤我無法指定'[String]'類型的值來鍵入'String?' (迅速)。這裏是我的代碼主要的代碼無法指定'[String]'類型的值來鍵入'String?' (Swift)

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

回答

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是一個字符串數組。我們可以迭代數組來獲取字符串,或者只使用前三個元素。

+0

我仍然得到同樣的錯誤(不能分配型「[字符串]」鍵入這樣做修正 –

+0

時添加的代碼執行的方法「洗牌「的字符串? '和'選擇'在你的問題 – BangOperator

+0

現在我得到致命的錯誤:意外地發現零,同時解開一個可選值 –

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(", ") 

我認爲應該解決它。

+0

所以是的,如其他評論中所見,我仍然得到這個致命錯誤:意外地發現零,同時展開一個可選值 –

+0

@RuchirMehta Somewhere在你的代碼中,你將一個'nil'值傳遞給'var',你已經用'!'定義了'var',這可能就是爲什麼你會得到這個錯誤。 – Burak

+1

@RuchirMehta我認爲這個錯誤是由你的代碼的其他部分引起的,你沒有在這個問題中顯示。我建議你找出錯誤發生的位置。然後,您可以提出有關錯誤的新問題。請記住告訴我們您試圖解決的問題!之後,你可以接受這個問題的答案之一。 – Sweeper

2

對於你的錯誤:「unexpectedly found nil while unwrapping an Optional value」,看看我的帖子關於他們,理解'!'和'?'對於飛速發展的關鍵: What are '!' and '?' marks used for in Swift

此外,作爲其他的答案也提到,你是返回數組值,而不是你應該給一個String值,然後將其分配給您的label.text值。對於這一點,你可以試試下面:

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

我看了你的帖子,我明白了,但我不知道我會在哪裏放置任何'?'的代碼。另外,當我輸入代碼時,它給了我一個錯誤,說我不能分配類型'()'來鍵入'String?' –

+0

@RuchirMehta OK,根據你所說的:「這是代碼行:altLabel.text = selectedThree [0] +」「+ selectedThree [1] +」「+ selectedThree [2]」and「... couldn分配類型'()'來鍵入'字符串?'「,問題是'altLabel.text = shuffled'中使用'混洗',返回'空數組'或'nil'。所以,看起來有一些你在你的方法中錯過了「Array Extension」 – Burak

+0

當我使用代碼「altLabel.text = selectedThree [0] +」「+ selectedThree [1] +」「+ selectedThree [2]「」,當我使用你給我的代碼「altLabel.text =」\(shuffled [0]),\(shuffled [1]),\(shuffled [2])「」。當我運行你的代碼時,「type'()'鍵入'String?'」錯誤,但現在沒有錯誤(反斜槓在那裏,它只是沒有顯示在註釋中) –

相關問題