测试一、编写九九乘法表
效果如下:
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("编写一个程序 打印出99乘法表")
for (i in 1..9) {
for (j in 1..i){
print("$j * $i = ${i*j}\t")
}
println()
}
}
Swift
/// 打印乘法口诀
private func printMultiplication() {
print("编写一个程序 打印出99乘法表")
for i in 1...9 {
for j in 1...i {
print("\(j) * \(i) = \(i*j) \t",terminator: "")
}
print("")
}
}
测试二、 打印1000以内质数
Kotlin
// 输出1000以内的质数
private fun printPrimes() {
println("打印出 1000 以内的素数")
for (n in 2..1000) {
for (m in 2 until n) {
if (n % m == 0) {
break
}
if (n == m+1) {
println(n)
}
}
}
}
Swift
/// 输出1000以内的质数
private func printPrimes() {
print("打印出 1000 以内的素数")
for n in 2...1000 {
for m in 2 ... n {
if (n % m == 0) {
break
}
if (n == m + 1) {
print(n)
}
}
}
}
测试三、为数组编写扩展方法,实现求和的功能,指定泛型为Int数据类型
Kotlin
// 扩展Array的求和方法
fun Array<Int>.sum():Int {
var sum = 0
this.forEach {
sum += it
}
return sum
}
// 实现一个泛型的公用方法
fun <T>Array<T>.sum() {
for (item in this)
println(item)
}
Swift
/// 当Array内的类型为整数时添加计算属性sum
extension Array where Element == Int {
var sum : Int {
var result = 0
self.forEach { (item) in
result += item
}
return result
}
}
测试四、Swift 协议、枚举、继承练习
- 枚举设置关联值
/// 编写一个枚举AnimalMoveType,其中走路关联脚的数量,飞翔关联翅膀数量
enum AnimalMoveType {
case walk(foot:Int)
case swim
case fly(wings:Int)
}
- 自定义协议
/// 编写 Animal 协议 协议中 规定一个函数func liveAt() -> String
protocol Animal {
var moveType: AnimalMoveType{get}
func liveAt() -> String
}
- 协议添加默认实现
/// 为Animal 协议添加默认实现,liveAt 默认返回"earth"
extension Animal {
func liveAt() -> String{
return "all the annimal live at earth"
}
}
- 编写类实现协议
class Dog: Animal {
var moveType: AnimalMoveType
init() {
moveType = .walk(foot:4)
print("this is dog")
}
func liveAt() -> String {
return "Dog liveAt house"
}
}
- 继承与方法重写
class Corgi: Dog {
override func liveAt() -> String {
return "Corgi liveAt yard"
}
}