Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

iphone - Multiplication table in 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

    }

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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("
")
print("(table)")

Gives…

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

To break that down…

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...