Use of unresolved identifier 'Singleton' Swift 3 - iphone

Here is my below code:
private static var __once: () = {
Singleton.instance = RtccManager()
if let instance = Singleton.instance {
instance.connectionParameters = instance.flattenConnectionParametersOverride(nil)
instance.currentStat = .sta_notConnected
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background).async {
instance.rtccConnect([:])
}
}
}()
var connectionParameters: [String : Any] = [:]
var currentStat: AppStatus = AppStatus.sta_notConnected
class var sharedInstance: RtccManager {
struct Singleton {
static var instance: RtccManager? = nil
static var token: Int = 0
}
_ = RtccManager.__once
return Singleton.instance!
}
I am getting error on line Singleton.instance = RtccManager() and line
if let instance = Singleton.instance
Error is: Use of unresolved identifier 'Singleton'
This error came after migrating to Swift 3.0
Any ideas on how can I resolve this error's?

If you're migrating your code It's should be a good idea to adapt your singleton creation mode to the new way suggested by Apple in their docs.
Here's an example
public class RtccManager
{
/*
Nested types
*/
public enum AppStatus
{
case sta_connected
case sta_notConnected
}
public static let sharedInstance: RtccManager = RtccManager()
public private(set) var connectionParameters: [String: Any]
public private(set) var currentStat: AppStatus
private init()
{
self.connectionParameters = [String: Any]()
// flattenConnectionParametersOverride
self.currentStat = .sta_notConnected
}
}

Related

Swift Generic parameter 'T' could not be inferred

I have a generic dictionary, and built a generic function to access that dictionary (to prevent concurrency access problems).
My (singleton) data class looks like:
class AppData {
static let genericDict: Dictionary<String, Any> = [:]
static func genericGet<T: Any>(_ objID: String) -> T {
let retVal: T
mySemaphore.wait()
retVal = genericDict[objID] as! T
mySemaphore.signal()
return retVal
}
}
However, when I call my function like so:
class SomeClass {
let product: SomeObj = AppData.genericGet(objID) as! SomeObj
}
I get the error:
Generic parameter 'T' could not be inferred
I both explicitly and implicitly cast the type to my desired value. Not sure what else I can do to fix this issue.
I've tried restarting XCode, does not help.
The real code:
public class AppData: ObservableObject {
static private var dataDirectory: Dictionary<String, Any> = Dictionary(minimumCapacity: 10000)
static let dataGetLock = DispatchSemaphore(value: 1)
static func get<T: Any>(_ objID: String) -> T? {
let retVal: T
dataGetLock.wait()
retVal = dataDirectory[objID] as! T
dataGetLock.signal()
return retVal
}
}
I get the error on the following two lines:
class StoreViewEnvironment: ObservableObject {
func initProductLoad(storeID: String) {
...
let liveStore: Store = AppData.get(storeID) as! Store
let liveMenu: Menu = AppData.get(liveStore.menuID) as! Menu
...
}
}
I don't approve of the way you're doing this (on the general grounds that Any is just about always a bad smell), but here's a version that compiles (just delete the Any constraint):
class AppData {
static let genericDict: Dictionary<String, Any> = [:]
static func get<T>(_ objID: String) -> T {
let retVal: T
retVal = genericDict[objID] as! T
return retVal
}
}
class SomeClass {
let product : String = AppData.get("yoho")
}

Unable to infer closure type in the current context in APIClient

I'm trying to migrate code from Swift 3.2 to Swift 4.2. When put in Xcode 10.1 I get this error.'Unable to infer closure type in the current context '. This is using YALAPIClient. Please help.
Unable to infer closure type in the current context
This I found on stack overflow. But I'm not using any try method here.Please help.
private func presentIndustrySearch() {
let dataProvider = RequestDataProvider { return IndustriesRequest() } /*error comes here*/
}
public class RequestDataProvider<Representation, Request>: DataProvider, NetworkClientInjectable
where
Request: SerializeableAPIRequest,
Request.Parser.Representation == [Representation]
{
public typealias Item = Representation
public typealias RequestConstructor = () -> Request
public private(set) var data = [Item]()
private let requestConstructor: RequestConstructor
public init(_ requestConstructor: #escaping RequestConstructor) {
self.requestConstructor = requestConstructor
}
public func loadData(before: () -> Void, after: #escaping (Error?) -> Void) {
let request: Request = self.requestConstructor()
before()
networkClient.execute(request: request, parser: request.parser, completion: { [weak self] task in
guard let `self` = self else { return }
if let data = task.value, data.count != 0 {
self.data.append(contentsOf: data)
after(nil)
} else if let error = task.error {
after(error as NSError)
} else {
let error = NSError.reachedEndOfPage()
after(error)
}
})
}
}
public protocol SerializeableAPIRequest: APIRequest {
associatedtype Parser: ResponseParser
var parser: Parser { get }
}
public struct IndustriesRequest: SerializeableAPIRequest, TokenizedAPIRequest, StubAPIRequest {
public private(set) var method = APIRequestMethod.get
public private(set) var path = "industries"
public private(set) var parser = KeyPathMappableArrayParser<[Industry]>(keyPath: "data")
public private(set) var parameters: [String: String]? = [:]
public private(set) var authenticationTokenRequired = true
public init(value: String = "") {
parameters!["term"] = value
}
}

Static string constant in swift evaluating as empty string ""

Why does my string constant kAppCacheKey evaluate to an empty string the first time I access it? It shows up as the string "myAccount" on subsequent calls to it.
Am I declaring static constants in the right way?
let kAppCacheKey = "myAccount"
class LoggedUser {
class var sharedInstance: LoggedUser {
struct Static {
static let instance = LoggedUser.loadFromCache()
}
return Static.instance
}
override private init() {
super.init()
}
private class func loadFromCache() -> LoggedUser {
//kAppCacheKey is evaluated as an empty string here for some reason
if let data = Locksmith.loadDataForUserAccount(kAppCacheKey) as? [String:String]
{
}
}

NSJSONSerialization json data from Swift dictionary containing struct as values

I am trying to convert a swift dictionary (that has String as keys and struct as values) into json data using NSJSONSerialization. But I am getting this error:
Cannot invoke 'dataWithJSONObject' with an argument list of type'([String : Vik.Version], options: NSJSONWritingOptions, error: nil)
Is there anything that I am missing. any help would be appreciated.
Thanks
Following is my code.
final class Vik: NSObject {
private struct Version {
private var name: String
private var filesToAdd = [String]()
private var filesToRemove = [String]()
init(name: String, filesToAdd: [String]?, filesToRemove: [String]?) {
self.name = name
if let filesToAdd = filesToAdd {
self.filesToAdd = filesToAdd
}
if let filesToRemove = filesToRemove {
self.filesToRemove = filesToRemove
}
}
}
......
......
......
private var changeLogDict = [String : Version]()
private func addToDirectory() {
.......
.......
let jsonData = NSJSONSerialization.dataWithJSONObject(self.changeLogDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
.......
.......
}
}
I figured it out. NSJSONSerialization.dataWithJSON method takes 'AnyObject' data type. Swift dictionary is a struct not an object and hence its complaining. Following line compiles fine
let jsonData = NSJSONSerialization.dataWithJSONObject(self.changeLogDict as NSDictionary, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

Cannot assign to the result of this expression with generics

I have the following generic class where I want to manage a string hash:
class NamedProfile<T> {
private var set = [String:T]()
private var profiles = [String]()
private let userDefaults = NSUserDefaults.standardUserDefaults()
private let profileName:String
var currentSet = ""
init(name:String, set:[String:T]) {
profileName = name
self.set = set
if let existingProfiles = userDefaults.objectForKey(name) as? [String] {
profiles = existingProfiles
}
for key in profiles {
if let existingProfile = userDefaults.objectForKey(profileNamed(name)) as? T {
set[key] = existingProfile // <-- error
}
}
}
private func profileNamed(name:String) -> String { return "\(profileName) \(name)" }
}
Why does the compiler croak in the above assignment?
In
init(name:String, set:[String:T]) {
// ...
set[key] = existingProfile // <-- error
// ...
}
set refers to the (immutable) method parameter.
Use self.set instead to refer to the property.