同時得到商和餘數的 quotientAndRemainder(dividingBy:)

在 Swift 裡做除法求商和餘數時,因為求商要用 /,求餘數要用 %,所以變成要除兩次才能得到商和餘數。

let number1 = 10let number2 = 3let quotient = number1 / number2let remainder = number1 % number2

其實是可以只除一次,一行就得到的,利用 Int 的 function quotientAndRemainder(dividingBy:)。

func quotientAndRemainder(dividingBy rhs: Int) -> (quotient: Int, remainder: Int)

quotientAndRemainder(dividingBy:) 回傳的資料是包含兩個東西的 tuple,包含了 quotient 和 remainder。

例子

let number1 = 10let number2 = 3let answer = number1.quotientAndRemainder(dividingBy: number2)answer.quotientanswer.remainder

讀取 quotient 和 remainder 即可取得商和餘數。

彼得潘的 Swift iOS App 開發問題解答集

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade