Differentiating Between a Struct and a Class in Swift

我们两清 提交于 2019-12-24 23:04:06

问题


I know why I would use a struct as opposed to a class, but how could I best tell which is being used by an API I'm using?

Obviously looking at the header file (or hopefully documentation) should make it immediately obvious. I am wondering if there is a way to know if the object I am using is a struct or class on face value though?


回答1:


Auto completion in Xcode knows the type of type:




回答2:


You can’t inherit from other structures or types. Classes have the ability to inherit functions, variables, and constants from parent classes.

In swift structs are value types while classes are reference types. Working with value types can make your code less error prone.

When you make a copy of a reference type variable, both variables are referring to the same object in memory. A change to one of the variables will change the other.

when you make a copy of a value type variable, the complete variable is copied to a new place in memory. A change to one of the copies will not change the other. If the copying of an object is cheap, it is far safer to make a copy than it is to share memory.




回答3:


I'm not sure what you mean by "face-value". You can test to see if an object is an instance of a class by getting it's MirrorType using reflect and checking for the MirrorType's objectIdentifier property, like this:

struct TestStruct { }
class TestClass { }

let testStruct = TestStruct()
let testClass = TestClass()

if let x = reflect(testStruct).objectIdentifier {
    println("I am a class...")
} else {
    println("I am not a class...")    // prints "I am not a class..."
}

if let x = reflect(testClass).objectIdentifier {
    println("I am a class...")        // prints "I am a class..."
} else {
    println("I am not a class...")
}

This answer may be outdated with the upcoming release of Swift 1.2 (I do not have the new xCode beta so I can't say for sure), which I understand has better object introspection, but this does do the trick.



来源:https://stackoverflow.com/questions/28833960/differentiating-between-a-struct-and-a-class-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!