随机获取一个字典项并打印出来

时间:2021-07-17 04:26:57

标签: swift dictionary random key func

我希望我的 swift 代码从字典中获取一个项目。根据我的理解,字典以字母表中的一个字母为键。我想要做的是在调试部分打印一个随机的女孩名字。每次按下按钮时都会打印一个新键和名称。

import UIKit

class ViewController: UIViewController {
    
    
    var girlsName = ["a": "Jessica Biel", "b": "Gwen Stefani","c":"Jessica Alba" ]
    
    var btn = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        [btn].forEach{
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
            $0.backgroundColor = UIColor(
                red: .random(in: 0.0...1),
                green: .random(in: 0.9...1),
                blue: .random(in: 0.7...1),
                alpha: 1
            )
            
        }
        btn.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        btn.addTarget(self, action: #selector(newark), for: .touchDown)
    }
    
    
    @objc func newark(){
        //print a letter and the corresponding name
        print()
        
    }
    }

0 个答案:

没有答案