2014-12-17 25 views
10

Tôi đang làm việc với Swift, Sprite-Kit và Xcode 6,tham số tùy chọn trong lớp khởi

Tôi đã một lớp học tuyên bố như thế này:

class Obstacles: SKSpriteNode 
{ 
    init(initTime: Int, speed: CGFloat, positionX: CGFloat, rotationSpeed: CGFloat) 
    { 
     self.initTime = initTime 
     self.rotationSpeed = rotationSpeed 
     self.positionX = positionX 

     super.init(texture: SKTexture(imageNamed: "Rectangle"), color: SKColor.redColor(), size: CGSize(width: 20, height: 20)) 
     self.speed = speed 
    } 

    var initTime: Int 
    var positionX: CGFloat 
    var rotationSpeed: CGFloat = 0 
} 

Vì vậy, tôi có thể gán một biến để lớp này như thế này:

var myVariable = Obstacles(initTime: 100, speed: 3.0, positionX: 10.0, rotationSpeed: 0.0) 

nhưng nếu ví dụ tôi không muốn để khởi tạo giá trị rotationSpeed ​​và có nó mặc định 0.0, làm thế nào tôi có thể quản lý để làm như vậy? Tôi không thể xóa thông số, kết quả là tôi gặp lỗi ...

Trả lời

12

Điều bạn muốn đặt giá trị mặc định cho rotationSpeed ​​nhưng bạn quên khai báo loại và gán giá trị mặc định. Thay vì nói rotationSpeed: 0.0) bạn sẽ có rotationSpeed: CGFloat = 0. Làm nhìn initializer của bạn như thế này:

init(initTime: Int, speed: CGFloat, positionX: CGFloat, rotationSpeed: CGFloat = 0) 

Bạn cũng có thể tìm thấy this SO bài hữu ích cũng

+0

tôi đã thấy bài này, nhưng sau khi đọc nó một lần nữa tôi đã hiểu cảm ơn, xấu của tôi – Drakalex

Các vấn đề liên quan