【问题标题】:Get Quote and its author using Swift使用 Swift 获取 Quote 及其作者
【发布时间】:2015-08-02 06:39:24
【问题描述】:

我对 Swift 很陌生,我正在尝试制作一个引用应用程序,但我想在单独的 UILabel 中显示引用和它自己的作者。但我不知道该怎么做,因为我有一个 randomQuote 函数,它为我的数组返回一个随机索引但数组只显示引用,我想获取随机引用并获取引用的作者。

这是我到目前为止所做的:

   var quotes = ["'Stay Hungry, Stay Foolish.'", "'Life is what happens while you are busy making other plans.'", ""]

var authors = ["Steve Jobs", "John Lennon"]



func getRandomQuote() -> String{
    //get random index
    var arrayCount = UInt32(quotes.count)
    var randomNumber = arc4random_uniform(arrayCount)
    var finalNumber = Int(randomNumber)

    return quotes[finalNumber]
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var randomImage: String = imageChange[randomNumber]
    self.motivationText.text = getRandomQuote()
    self.imageInspire.image = UIImage(named: randomImage)
}

我正在考虑使用字典,但我认为它不起作用:/

【问题讨论】:

    标签: arrays swift random


    【解决方案1】:

    如果您的作者和引文的顺序始终相同,您可以对引文和作者数组使用相同的 finalNumber。

    您可以在 getRandomQuote 中设置两个标签并删除返回的字符串,然后您可以从 viewDidLoad 中调用它。

    字典可以工作,您可以出于随机原因将其键视为数组,然后只需使用键/值对来填充您的标签。

    如果引用和作者始终处于相同顺序的示例:

    func getRandomQuote() {
    //get random index
    var arrayCount = UInt32(quotes.count)
    var randomNumber = arc4random_uniform(arrayCount)
    var finalNumber = Int(randomNumber)
    
    self.motivationText.text = quotes[finalNumber]
    self.authorName.text = authors[finalNumber] // Just an assumption on label name
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        getRandomQuote()
    
    }
    

    字典示例:

    let quotesWithAuthors = ["Steve Jobs":"Stay Hungry, Stay Foolish","Alan Kay":"Simple things should be simple, complex things should be possible","Bill Gates":"I'm not fake Steve Jobs"]
    
    let authorsArray = quotesWithAuthors.keys.array
    
    let randomQuoteKeyIndex = Int(arc4random_uniform(UInt32(authorsArray.count - 1)))
    
    self.authorName.text    = authorsArray[randomQuoteKeyIndex]
    self.otivationText.text = quotesWithAuthors[authorsArray[randomQuoteKeyIndex]]
    

    从执行的角度来看,它们本质上非常相似,但以这种方式存储可能更容易。尽管如果您使用作者姓名作为字典有来自同一作者的多个引用,您可能会遇到问题 - 在这种情况下,您可能需要翻转作者和引用。

    【讨论】:

    • 对不起,你能告诉我一些代码来理解吗?哈哈
    • 添加了一个代码示例,稍后再添加一个。
    猜你喜欢
    • 2015-12-02
    • 2014-03-12
    • 2017-05-07
    • 1970-01-01
    • 2021-03-15
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多