Swift: Sharing Properties Among Struct Instances Using 'static'
In Swift, you can create a property that is shared among all the struct values by using the static keyword. Here's an example: \n\nswift\nstruct MyStruct {\n static var sharedProperty: Int = 0\n var instanceProperty: Int = 0\n}\n\nvar struct1 = MyStruct()\nvar struct2 = MyStruct()\n\nstruct1.sharedProperty = 10\nstruct2.sharedProperty = 20\n\nprint(struct1.sharedProperty) // Output: 20\nprint(struct2.sharedProperty) // Output: 20\nprint(struct1.instanceProperty) // Output: 0\nprint(struct2.instanceProperty) // Output: 0\n\n\nIn this example, the sharedProperty is a static property and is shared among all instances of the MyStruct struct. Any changes made to this property will be reflected in all instances. On the other hand, instanceProperty is an instance property and each struct instance will have its own separate value for it.
原文地址: https://www.cveoy.top/t/topic/n3Kw 著作权归作者所有。请勿转载和采集!