Swift ios中的乘法表 [英] Multiplication table in Swift ios

查看:25
本文介绍了Swift ios中的乘法表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何快速制作乘法表并使用

I am learning how to make a multiplication table in swift and used

override func viewDidLoad() {
    let n = Int(str)!

    while (i<=10) {


       let st = "\(n) * \(i) = \(n * i)"
       lbl.text = st

        i += 1

    }

这个代码.我有一个标签,我想在其中显示表格,但问题是只显示了最后一个结果,即 2*10 = 20,而不是所有其他值.我很困惑该怎么办,请帮助我做什么,以便显示所有值.

this code. i have a label in which i want to show the table, but the problem is that only the last result which is say 2*10 = 20 is showing and not all the other value. i am confused what to do, please help what to do so that all the values are displayed.

推荐答案

很高兴您决定学习 Swift.您走在正确的轨道上,但正如其他人所说,您循环的最后一次迭代正在替换 lbl.text 的内容.

Glad you've decided to learn Swift. You're on the right track, but as others have said, your final iteration of the loop is replacing the contents of lbl.text.

有很多方法可以实现您想要的目标,但对于此类问题,我建议您从 Playground 开始工作,而不是担心标签、viewDidLoad 等问题.

There are many ways to achieve what you want, but for problems like this I'd suggest starting off working in a playground rather than worrying about labels, viewDidLoad and suchlike.

这是一个很好的 Swift-y 方式来做你想做的事情

Here's a nice Swift-y way to do what you want

let n = 12
let table = Array(0...10).map({"\(n) * \($0) = \(n * $0)"}).joinWithSeparator("\n")
print("\(table)")

给...

12 * 0 = 0
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120

分解一下……

      // Take numbers 0 to 10 and make an array 
Array(0...10).

      // use the map function to convert each member of the array to a string
      // $0 represents each value in turn. 
      // The result is an array of strings
map({"\(n) * \($0) = \(n * $0)"}).

      // Join all the members of your `String` array with a newline character
joinWithSeparator("\n")

你自己试试.在 Xcode 中,File -> New -> Playground,然后粘贴该代码.祝你好运!

Try it for yourself. In Xcode, File -> New -> Playground, and just paste in that code. Good luck!

这篇关于Swift ios中的乘法表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆