swift - 使用结构进行转换时的对称性。什么是最佳实践?

标签 swift structure

我一直在使用 Swift,并且编码了一个明显的转换结构:

struct MutableAngle {
    var degrees : CGFloat
    var radians : CGFloat {
        return degrees * CGFloat(M_PI) / 180.0
    }

    init(inRadians : CGFloat) {
        degrees = inRadians * 180.0 / CGFloat(M_PI)
    }
    init(inDegrees : CGFloat) {
        degrees = inDegrees
    }
}

现在这很好,但不优雅,因为它不对称地处理角度和弧度,尽管它确实提供了可变性。这实际上是一个应该称为“度数”的结构,它可以提供弧度。例如,我可以写:

var angle : MutableAngle
angle.degrees = 45.0

但不是

var angle : MutableAngle
angle.radians = 0.75

这是最终版本:

struct Angle {
  let degrees : CGFloat
  let radians : CGFloat

  init(inRadians : CGFloat ) {
    radians = inRadians
    degrees = radians * CGFloat (180 / M_PI)
  }
  init(inDegrees : Float ) {
    degrees = inDegrees
    radians = degrees * CGFloat (M_PI / 180)
  }
}

使用如下:

var alpha = Angle(inDegrees: 45)
alpha.degrees // returns 45
alpha.radians // returns 0.7853982

// alpha.radians = 0.9  ... is now illegal with let constants
// must use constructor ... provided alpha was defined using 'var'
// i.e. the struct itself is mutable
alpha = Angle(inRadians: 0.9)
alpha.radians // returns 0.7853982
alpha.degrees // returns 45

从 var 切换到 let 使其可变/不可变,具体取决于 alpha 的定义方式,我现在不得不使用构造函数,这很好。所以它是对称的。它还有一个优点是不需要每次使用弧度时都需要计算。

最佳答案

这里有两件事:

  1. 在 Swift 中,值类型不需要单独的可变类型 - 这由使用 letvar 实例化类型的人来处理。

  2. 您的 radians 计算属性只有一个 getter - 您可以使用 setter 和 getter 执行您想要的操作。

我的实现:

struct Angle {
    var degrees : CGFloat = 0
    var radians : CGFloat {
        get {
            return degrees * CGFloat(M_PI) / 180.0
        }
        set {
            degrees = newValue * 180.0 / CGFloat(M_PI)
        }
    }

    init(inRadians : CGFloat) {
        radians = inRadians
    }
    init(inDegrees : CGFloat) {
        degrees = inDegrees
    }
}

用途:

// immutable
let angle = Angle(inDegrees: 180)
println(angle.radians)
// next line gives an error: can't assign to an immutable instance
angle.radians = angle.radians * 2

// mutable copy
var mutableAngle = angle
mutableAngle.degrees = 10
println(mutableAngle.radians)
// 0.1745...
mutableAngle.radians = CGFloat(M_PI)
println(mutableAngle.degrees)
// 180.0

关于swift - 使用结构进行转换时的对称性。什么是最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024100/

相关文章:

swift - 如何在 cocoa 中将pdfview更改为单页模式

c - 在 C 中使用邻接列表初始化基于数组的图形时出现问题

swift - 如何获取目标文件格式(或文件)的 Finder "Open in app"对话框中显示的应用程序列表?

ios - 点击一个单元格也会影响其他单元格

c - 将结构写入c中的文件

swift - 如何在 Swift 中使用结构组件初始化字典

c++ - 结构数组,其中包含数组。不会编译

将数组的元素复制到 C 中的链表

ios - 如何更改每个 View Controller 的 UINavigationBar

ios - 当父 UIview 约束减少时,如何使 swift UIview 子元素自动收缩?