3
\$\begingroup\$

In a Swift project, I have a class should be used as a singleton:

 class NearFieldManager : NSObject{
 static let shared = NearFieldManager()
 var dataToTransfer:Any!
 }

This class helps me communicate between several nearby devices and the dataToTransfer is some information each device is advertising about itself. What makes me wondering about this class is that each time I call it goes like this:

let manager = NearFieldManager.shared
shared.dataToTransfer = "some data"

First, I am creating a reference to the manager and line after it I set some value on its property. How can I improve this design?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 8, 2017 at 6:01
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Assuming the dataToTransfer is always the same for a specific device, you can create this data in init()

class NearFieldManager {
 static let shared = NearFieldManager()
 private let dataToTransfer: Any
 private init() { //private to forbid instantiation 
 self.dataToTransfer = methodToCreateDeviceData()
 }
}
answered Jan 8, 2017 at 7:11
\$\endgroup\$
2
  • \$\begingroup\$ I'd get rid of that redundant dataToTransfer local var. It doesn't contribute anything but visual clutter. \$\endgroup\$ Commented Jan 23, 2017 at 21:15
  • \$\begingroup\$ @Alexander agree. \$\endgroup\$ Commented Jan 24, 2017 at 3:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.