Swift学习小结之对象和类

前端之家收集整理的这篇文章主要介绍了Swift学习小结之对象和类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit

var str = "Hello,playground"
//对象和类
class Shape {
   var numberofSides = 0
    func simpleDescription() ->String {
    return "A shape with \(numberofSides) sides"
    
    }
}
var shape =  Shape()
shape.numberofSides = 7
var shapeDescription = shape.simpleDescription()

class NameShape{
    var numberofSides :Int = 0
    var name : String
      init(name : String){
        self.name = name
    }
    func simpleDescription() ->String{
        return "A shape with \(numberofSides) sides"
      }
}

class Square : NameShape {
    var sideLenth: Double
    init(sideLenth : Double,name : String)
    {
        self.sideLenth = sideLenth
        super.init(name: name)
        numberofSides = 4
        }
    func area() ->Double{
      return sideLenth * sideLenth
         }
    override func  simpleDescription() -> String {
        return " A squre with sides of lenth \(sideLenth)"
    }
}
let  test = Square(sideLenth: 5.2,name: "my test Square")
test.area()
test.simpleDescription()

class EquilateralTriangle : NameShape {
    var sideLength: Double = 0.0
    init(sideLength : Double,name : String){
     self.sideLength = sideLength
        super.init(name: name)
        numberofSides = 3
        }
    var perimeter : Double {
        get {
          return 3.0 * sideLength
        }
        set {
        
          sideLength = nesValue / 3.0
        }
    
    
    }
    override func simpleDescription() -> String {
        return " An equilateral triagle with sides of lenth \(sideLength)"
    }
    
}
var triangle =  EquilateralTriangle (sideLength: 3.1,name: " a triangle")
 triangle.perimeter
 triangle.perimeter = 9.9
 triangle.sideLength
 
class TriangleAndSquare {
    var triangle : EquilateralTriangle{
        willSet {
         square.sideLength = newValue.sideLength
        
        }
    }
    var square : Square {
        willset {
        
          triangle.sideLength = newValue.sideLength
            
        
        }
        
    
    }
    init ( size : Double,name : String){
      square = Square(sideLenth: size,name: name)
     triangle =  EquilateralTriangle(sideLength: size,name: name)
        
    
    
    }
  
}

var triangleAndSquuare = TriangleAndSquare(size: 10,name: "another test shape")
triangleAndSquuare.square.sideLenth
triangleAndSquuare.triangle.sideLength
triangleAndSquuare.square =  Square(sideLenth: 50,name: "Larger square")
triangleAndSquuare.triangle.sideLength

class Counter {
    var count : Int = 0
    func incrementBy(amount : Int,numberofTimes times :Int){
         count +=  amount * times
    
    }
}
var couter = Counter()
couter.incrementBy(2,numberofTimes: 7)


原文链接:https://www.f2er.com/swift/327571.html

猜你在找的Swift相关文章