How to get systemLocaleCountryCode in swift 3? - ios

i swift 2 i was getting the systemLocale using the bellow code:
let systemLocaleCountryCode = NSLocale.systemLocale().objectForKey(NSLocaleCountryCode) as? String
but now i in swift 3 , i am receiving the bellow error :
cannot call value of non function type locale
then once i changed it to :
let systemLocaleCountryCode = NSLocale.systemLocale.objectForKey(NSLocaleCountryCode) as? String
I've received another error:
value of type Locale has no member objectForKey
what's the problem ? How to fix it ?

use like
if let systemLocaleCountryCode = (Locale.system as NSLocale).object(forKey: .countryCode) as? String {
print(systemLocaleCountryCode)
}

In Swift3
change to
let systemLocaleCountryCode = (NSLocale.system as NSLocale).object(forKey: .countryCode) as? String

You can try this:
if let systemLocaleCountryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String
{
print(systemLocaleCountryCode)
}

Related

swift 3.0 How can I access `AnyHashable` types in `Any` in Swift 3?

I'm using sqlite file to get the diaryEntriesTeacher from the authorId. it generates the following object of authorId when I print the variable authorId is nil
Code :-
func applySelectQuery() {
checkDataBaseFile()
objFMDB = FMDatabase(path: fullPathOfDB)
objFMDB.open()
objFMDB.beginTransaction()
do {
let results = try objFMDB.executeQuery("select * from diaryEntriesTeacher", values: nil)
while results.next() {
let totalCount = results.resultDictionary
let authorId = totalCount?["authorId"]!
print("authorId",authorId)
}
}
catch {
print(error.localizedDescription)
}
print(fullPathOfDB)
self.objFMDB.commit()
self.objFMDB.close()
}
output
This is how you access Dictionary of [AnyHashable : Any]
var dict : Dictionary = Dictionary<AnyHashable,Any>()
dict["name"] = "sandeep"
let myName : String = dict["name"] as? String ?? ""
In your case
let authorId = totalCount?["authorId"] as? String ?? ""
We need to convert the property we are trying to access to AnyHashable before using it.
In your case :
do {
let results = try objFMDB.executeQuery("select * from diaryEntriesTeacher", values: nil)
while results.next() {
let totalCount = results.resultDictionary
let authorId = totalCount?[AnyHashable("authorId")]!
print("authorId",authorId)
}
This is Swift. Use strong types and fast enumeration. Dictionary<AnyHashable,Any> is the generic type of a dictionary and can be cast to <String,Any> as all keys seem to be String.
do
if let results = try objFMDB.executeQuery("select * from diaryEntriesTeacher", values: nil) as? [[String:Any]]
for item in results {
let authorId = item["authorId"] as? String
let studentName = item["studentName"] as? String
print("authorId", authorId ?? "n/a")
print("studentName", studentName ?? "n/a")
}
}
....

Type 'Any' has no subscript members NSIndexPath and indexPath Swift 3

I have recently converted my code to Swift 3.0 from Swift 2
I am getting value like this
let productRequestID = Int(self.array[(indexPath as NSIndexPath).item]["ProductRequest"]!!["product_request_id"] as! NSString as String)!
let requestTitle = ((self.array[(indexPath as NSIndexPath).item]["ProductRequest"]!!["request_title"] as! NSString) as String) as String
Now I am getting an error Type 'Any' has no subscript members
self.array[(indexPath as NSIndexPath).item]["ProductRequest"] This line returns the object in Any so compiler unable to find the key product_request_id as Any type.
So you have to type cast into Dictionary<Any> then you can get your value like this:
let dict = self.array[(indexPath as NSIndexPath).item]["ProductRequest"] as? Dictionary<Any>
let productRequestID = Int(dict!["ProductRequest"]as? String ?? "")
let requestTitle = dict!["request_title"]as? String ?? ""

Swift NSDictionary Child types

I'm having a lot of frustration with Swift when it comes to working with Dictionaries and NSDictionaries.
I am pulling data from a server. One of the values is a Bool.
I started with a Swift Dictionary and moved to NSDictionary out of frustration. However, I still cannot get the values from the dictionary.
All of the following fail with contradictory errors:
let unread:Bool = data!["unread"] as! Bool
let unread:Bool = data?["unread"] as! Bool
let unread:Bool = data?.objectForKey("unread") as! Bool
let unread:NSNumber = data?["unread"] as! NSNumber
error: Could not cast value of type 'NSTaggedPointerString' (0x110c1eae8) to 'NSNumber' (0x10e0ab2a0).
Okay, looks like that data is coming in as a String... let's try:
let unreadStr:String = data!["unread"] as! String
let unreadStr:NSString = data!["unread"] as! NSString
error: Could not cast value of type '__NSCFBoolean' (0x1097413b8) to 'NSString' (0x106bcdb48).
So I'm confused. When I try to convert it to a Bool it says I cannot convert a String to a Number. When I try to convert it to a String, it says I cannot convert a number to a string.
Here is what the data looks like:
Optional({
senderId = 10154040;
sent = 1460844986973;
text = "Test Message 1";
unread = false;
})
You should try something along these lines:
let data: [String : Any] = ["first" : "test", "second" : 2, "third" : true]
let first = data["first"] as! String
let second = data["second"] as! Int
let third = data["third"] as! Bool
print(first)
print(second)
print(third)

text field receiving optional('value") instead of "value "

I'm trying to pass a text that is correct api put in swift he arrives with the message of "optional". this is my code:
let accountValues:NSArray = account!.accountNumber.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "-"))
self.accountTextField.text = accountValues.objectAtIndex(0) as? String
self.accountDigitTextField.text = accountValues.objectAtIndex(1) as? String
When retrieving the value, use ! after the value. The downcast should force unwrap any optionals. Anything set as? can be force unwrapped by using !.
For example,
let intString = 7 as? String
print(intString!)
This should print "7", rather than Optional("7")
please replace these lines :
self.accountTextField.text = accountValues.objectAtIndex(0) as? String
self.accountDigitTextField.text = accountValues.objectAtIndex(1) as? String
by :
self.accountTextField.text = (accountValues.objectAtIndex(0) as! String)
self.accountDigitTextField.text = (accountValues.objectAtIndex(1) as! String)
You're using Optional Value "As? String". So, it will return an Optional('value').
Try this:
let accountValues:NSArray = account!.accountNumber.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "-"))
self.accountTextField.text = "\(accountValues.objectAtIndex(0))"
self.accountDigitTextField.text = "\(accountValues.objectAtIndex(1))"

Extracting values from NSDictionary to individual variables

I really thought this was Xcode playing up as I can't for the life of me see what is causing this error in a fairly simple piece of Swift code but after restarting cleaning the project, restarting Xcode, and restarting my MacBook I'm still getting the same error.... But why!!??!!
Here is the code
// Loop through records saving them
for recordItem in records {
if let record: NSDictionary = recordItem as? NSDictionary {
let time: String = record["time"] as! String
let record: String = record["record"] as! String
let recordId: String = record["record_id"] as! String
let saveTime: String = record["save_time"] as! String
let setId: String = record["set_id"] as! String
// Does more stuff
}
}
records is an NSArray and it is made from data downloaded from a remote server.
All is fine until the line beginning let recordId. This and the two lines below it are giving an error - Cannot subscript a value of type 'String' with an index of type 'String'
Why? And why is there no problem with the 2 lines above? And how do I fix it?
Any help is greatly appreciated as I'm at a bit of a dead end.
You are using the variable record to unwrap the optional recordItem but then you are re-assigning record as record["record"] - so from this point on it becomes a String, not a Dictionary - resulting in the error message Cannot subscript a value of type 'String' with an index of type 'String'
You just need to change one of the record variables
for recordItem in records {
if let unwrappedRecord: NSDictionary = recordItem as? NSDictionary {
let time: String = unwrappedRecord["time"] as! String
let record: String = unwrappedRecord["record"] as! String
let recordId: String = unwrappedRecord["record_id"] as! String
let saveTime: String = unwrappedRecord["save_time"] as! String
let setId: String = unwrappedRecord["set_id"] as! String
// Does more stuff
}
}
The problem is here, you are declaring record as a String, previously it was NSDictionary and due to scope the record in record["record_id"] is String not NSDictionary. Quick fix is to change the name as I did
let time: String = record["time"] as! String
let record1: String = record["record"] as! String
let recordId: String = record["record_id"] as! String
let saveTime: String = record["save_time"] as! String
let setId: String = record["set_id"] as! String

Resources