測(cè)試一妨托、編寫(xiě)九九乘法表
效果如下:
1 x 1 = 1
1 x 2 = 2 2 x 2 = 4
1 x 3 = 3 2 x 3 = 6 3 x 3 = 9
1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16
1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25
1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35 6 x 7 = 42 7 x 7 = 49
1 x 8 = 8 2 x 8 = 16 3 x 8 = 24 4 x 8 = 32 5 x 8 = 40 6 x 8 = 48 7 x 8 = 56 8 x 8 = 64
1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 45 6 x 9 = 54 7 x 9 = 63 8 x 9 = 72 9 x 9 = 81
Kotlin
// 打印乘法口訣
private fun printMultiplication() {
println("編寫(xiě)一個(gè)程序 打印出99乘法表")
for (i in 1..9) {
for (j in 1..i){
print("$j * $i = ${i*j}\t")
}
println()
}
}
Swift
/// 打印乘法口訣
private func printMultiplication() {
print("編寫(xiě)一個(gè)程序 打印出99乘法表")
for i in 1...9 {
for j in 1...i {
print("\(j) * \(i) = \(i*j) \t",terminator: "")
}
print("")
}
}
測(cè)試二缸榛、 打印1000以?xún)?nèi)質(zhì)數(shù)
Kotlin
// 輸出1000以?xún)?nèi)的質(zhì)數(shù)
private fun printPrimes() {
println("打印出 1000 以?xún)?nèi)的素?cái)?shù)")
for (n in 2..1000) {
for (m in 2 until n) {
if (n % m == 0) {
break
}
if (n == m+1) {
println(n)
}
}
}
}
Swift
/// 輸出1000以?xún)?nèi)的質(zhì)數(shù)
private func printPrimes() {
print("打印出 1000 以?xún)?nèi)的素?cái)?shù)")
for n in 2...1000 {
for m in 2 ... n {
if (n % m == 0) {
break
}
if (n == m + 1) {
print(n)
}
}
}
}
測(cè)試三吝羞、為數(shù)組編寫(xiě)擴(kuò)展方法,實(shí)現(xiàn)求和的功能内颗,指定泛型為Int數(shù)據(jù)類(lèi)型
Kotlin
// 擴(kuò)展Array的求和方法
fun Array<Int>.sum():Int {
var sum = 0
this.forEach {
sum += it
}
return sum
}
// 實(shí)現(xiàn)一個(gè)泛型的公用方法
fun <T>Array<T>.sum() {
for (item in this)
println(item)
}
Swift
/// 當(dāng)Array內(nèi)的類(lèi)型為整數(shù)時(shí)添加計(jì)算屬性sum
extension Array where Element == Int {
var sum : Int {
var result = 0
self.forEach { (item) in
result += item
}
return result
}
}
測(cè)試四钧排、Swift 協(xié)議、枚舉均澳、繼承練習(xí)
- 枚舉設(shè)置關(guān)聯(lián)值
/// 編寫(xiě)一個(gè)枚舉AnimalMoveType,其中走路關(guān)聯(lián)腳的數(shù)量恨溜,飛翔關(guān)聯(lián)翅膀數(shù)量
enum AnimalMoveType {
case walk(foot:Int)
case swim
case fly(wings:Int)
}
- 自定義協(xié)議
/// 編寫(xiě) Animal 協(xié)議 協(xié)議中 規(guī)定一個(gè)函數(shù)func liveAt() -> String
protocol Animal {
var moveType: AnimalMoveType{get}
func liveAt() -> String
}
- 協(xié)議添加默認(rèn)實(shí)現(xiàn)
/// 為Animal 協(xié)議添加默認(rèn)實(shí)現(xiàn),liveAt 默認(rèn)返回"earth"
extension Animal {
func liveAt() -> String{
return "all the annimal live at earth"
}
}
- 編寫(xiě)類(lèi)實(shí)現(xiàn)協(xié)議
class Dog: Animal {
var moveType: AnimalMoveType
init() {
moveType = .walk(foot:4)
print("this is dog")
}
func liveAt() -> String {
return "Dog liveAt house"
}
}
- 繼承與方法重寫(xiě)
class Corgi: Dog {
override func liveAt() -> String {
return "Corgi liveAt yard"
}
}