【问题标题】:Cannot assign value of type [String] to type String? with text label无法将 [String] 类型的值分配给 String 类型?带文字标签
【发布时间】:2016-07-09 15:14:31
【问题描述】:

我在将 [String] 值分配给 Label 时遇到问题。 (或 - 更好 - 到 UITableView)。我收到错误“无法将 [String] 类型的值分配给 String 类型?”

我试过 as?斯特格和作为!字符串,但这也不能很好地工作。代码:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!

let cal = NSCalendar.currentCalendar()
let fmt = NSDateFormatter()
var auctionDates = [String]()

let textCellIdentifier = "TextCell"

override func viewDidLoad() {
    super.viewDidLoad()

    fmt.dateFormat = "(EEE)"
    fmt.locale = NSLocale(localeIdentifier: "pl_PL")

    var date = cal.startOfDayForDate(NSDate())

    while auctionDates.count < 7 {
       let weekDay = cal.component(.Weekday, fromDate: date)
       if weekDay != 0 {
            auctionDates.append(fmt.stringFromDate(date))
       }
       date = cal.dateByAddingUnit(.Day, value: 1, toDate: date, options: NSCalendarOptions(rawValue: 0))!
    }
    print(auctionDates)
    self.myLabel.text = auctionDates

}
}

任何帮助都会很棒;)

【问题讨论】:

  • 我知道我可以用 self.myLabel.text = "(auctionDates[0]), (auctionDates[1]), (auctionDates[2]), (auctionDates[3]), (auctionDates[4]), (auctionDates[5]), (auctionDates[6])" 但是这个选项很糟糕。
  • 不相关,但为什么要硬编码语言环境来格式化日期?波兰以外的人可能更喜欢以自己的格式查看日期。还要注意NSDateFormatter 已经有shortWeekdaySymbols 属性来获取工作日名称数组。不需要你写的所有代码。

标签: ios arrays swift string uitableview


【解决方案1】:
  • auctionDates 是一个数组(字符串列表)
  • text 需要一个单个字符串(不是列表)

解决方法有很多,其中之一就是扁平化列表

self.myLabel.text = auctionDates.joinWithSeparator(", ")

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多