Trying to create a countdown timer, but I can't get past this error:
Cannot invoke 'dateComponents' with an argument list of type '(NSCalendar.Unit.Type, from: NSData, to: Date?)'
my code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var TimerLable: UILabel!
let formatter = DateFormatter()
let userCleander = Calendar.current;
let CalenderComponent : NSCalendar.Unit = [
NSCalendar.Unit.year,
NSCalendar.Unit.month,
NSCalendar.Unit.day,
NSCalendar.Unit.hour
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func printTime()
{
formatter.dateFormat = "dd/MM/yy hh:mm a"
let StartTime = NSData()
let EndTime = formatter.date(from: "10/08/19 12:00 a")
let TimeDifference = userCleander.dateComponents(NSCalendar.Unit, from: StartTime, to: EndTime)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The main issue which causes the error is just a typo. StartTime is supposed to be NSDate not NSData.
Basically don't use NS... classes if there is a Swift native counterpart (Calendar, Date etc).
The Swift 3+ code is
let formatter = DateFormatter()
let userCalendar = Calendar.current
let calendarComponents : Set<Calendar.Component> = [ .year, .month, .day, .hour]
func printTime()
{
formatter.dateFormat = "dd/MM/yy hh:mm a"
let startTime = Date()
let endTime = formatter.date(from: "10/08/19 12:00 am")!
let timeDifference = userCalendar.dateComponents(calendarComponents, from: startTime, to: endTime)
}
Two notes:
According to the naming guidelines variable names start with a lowercase letter
The date format does not match the date string and the created date needs to be unwrapped.
I am new to Swift and trying to learn how to implement NSTreeController with NSOutlineView. I've been following several guides which shows such examples, but I keep getting an error. I followed step by step and/or try to run their source codes if available, but I was getting same error. I come to think there is some change in Swift 4 which makes these Swift 3 examples to produce error. As there are not many examples done in Swift 4, I decided I'd give a try by asking the question here.
The error I'm getting is:
this class is not key value coding-compliant for the key isLeaf.
I believe that error is coming from the key path set up for NSTreeController:
However I am not sure what needs to be done to fix the error.
I have simple model class called Year.
class Year: NSObject {
var name: String
init(name: String) {
self.name = name
}
func isLeaf() -> Bool {
return true
}
}
My view controller looks like this.
class ViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
#IBOutlet weak var outlineView: NSOutlineView!
#IBOutlet var treeController: NSTreeController!
override func viewDidLoad() {
super.viewDidLoad()
addData()
outlineView.delegate = self
outlineView.dataSource = self
}
func addData() {
let root = ["name": "Year", "isLeaf": false] as [String : Any]
let dict: NSMutableDictionary = NSMutableDictionary(dictionary: root)
dict.setObject([Year(name: "1999"), Year(name: "2000")], forKey: "children" as NSCopying)
treeController.addObject(dict)
}
func isHeader(item: Any) -> Bool {
if let item = item as? NSTreeNode {
return !(item.representedObject is Year)
} else {
return !(item is Year)
}
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
if isHeader(item: item) {
return outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "HeaderCell"), owner: self)!
} else {
return outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "DataCell"), owner: self)!
}
}
}
When I run the program, it causes no issue, but when I expand the node to show the two children of the root, it is giving the error I mentioned above.
Because is isLeaf is used in KVO by NSOutlineView, you have to add #objc in front of isLeaf function:
#objc func isLeaf() -> Bool {
return true
}
The class to which you are binding needs to be KVO compliant.
So, it needs to be a subclass of NSObject.
And the objc runtime needs access.
One way to do this:
#objcMembers
class FileSystemItem: NSObject {
Or, you can annotate each field/function with #objc
Full Example
How can I get the currency symbols for the corresponding currency code with Swift (macOS).
Example:
EUR = €1.00
USD = $1.00
CAD = $1.00
GBP = £1.00
My code:
var formatter = NSNumberFormatter()
formatter.currencySymbol = getSymbol(currencyCode)
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
let number = NSNumber(double: (amount as NSString).doubleValue)
let amountWithSymbol = formatter.stringFromNumber(number)!
getSymbol(_ currencyCode: String) -> String
or.. is there a better way?
A bit late but this is a solution I used to get the $ instead of US$ etc. for currency symbol.
/*
* Bear in mind not every currency have a corresponding symbol.
*
* EXAMPLE TABLE
*
* currency code | Country & Currency | Currency Symbol
*
* BGN | Bulgarian lev | лв
* HRK | Croatian Kuna | kn
* CZK | Czech Koruna | Kč
* EUR | EU Euro | €
* USD | US Dollar | $
* GBP | British Pound | £
*/
func getSymbol(forCurrencyCode code: String) -> String? {
let locale = NSLocale(localeIdentifier: code)
return locale.displayNameForKey(NSLocaleCurrencySymbol, value: code)
}
Basically this creates NSLocale from your currency code and grabs the display attribute for the currency. In cases where the result matches the currency code for example SEK it will create new country specific locale by removing the last character from the currency code and appending "_en" to form SE_en. Then it will try to get the currency symbol again.
Swift 3 & 4
func getSymbol(forCurrencyCode code: String) -> String? {
let locale = NSLocale(localeIdentifier: code)
if locale.displayName(forKey: .currencySymbol, value: code) == code {
let newlocale = NSLocale(localeIdentifier: code.dropLast() + "_en")
return newlocale.displayName(forKey: .currencySymbol, value: code)
}
return locale.displayName(forKey: .currencySymbol, value: code)
}
The answer may be late but hopefully this helps clarify the root cause.
Problem
Currency code does not imply locale and region
The reason why CAD becomes CA$ is probably because NSLocale looks up the first matching currency code, and for CAD, these are the matching localeIdentifiers in order of NSLocale.availableLocaleIdentifiers
1. Optional("CA$") Optional("CA") iu_CA
2. Optional("$") Optional("CA") fr_CA
3. Optional("$") Optional("CA") en_CA
iu_CA is Inuktitut but I'm not sure why it's listed as CA$, but I hope the point is clear.
Similarly in CNY (Chinese Yuan):
1. Optional("CN¥") Optional("CN") en_CN
2. Optional("¥") Optional("CN") yue_CN
3. Optional("¥") Optional("CN") bo_CN
4. Optional("¥") Optional("CN") zh_CN
5. Optional("¥") Optional("CN") ug_CN
6. Optional("¥") Optional("CN") ii_CN
The reason for showing CN¥ when en_CN is probably because JPY also uses ¥.
In CHF (Switzerland Franc), they do not have a one-letter symbol:
1. Optional("CHF") Optional("LI") gsw_LI
2. Optional("CHF") Optional("CH") de_CH
...
9. Optional("CHF") Optional("CH") en_CH
10. Optional("CHF") Optional("CH") it_CH
Solution
Many apps vary, but this is the steps I took that I am happy with for my application:
Find matching locale candidates using currency code lookup from all locale identifiers
Pick the shortest symbol from the candidates
Store the symbol somewhere so that it doesn't have to be computed each time
Implementation
func getSymbolForCurrencyCode(code: String) -> String {
var candidates: [String] = []
let locales: [String] = NSLocale.availableLocaleIdentifiers
for localeID in locales {
guard let symbol = findMatchingSymbol(localeID: localeID, currencyCode: code) else {
continue
}
if symbol.count == 1 {
return symbol
}
candidates.append(symbol)
}
let sorted = sortAscByLength(list: candidates)
if sorted.count < 1 {
return ""
}
return sorted[0]
}
func findMatchingSymbol(localeID: String, currencyCode: String) -> String? {
let locale = Locale(identifier: localeID as String)
guard let code = locale.currencyCode else {
return nil
}
if code != currencyCode {
return nil
}
guard let symbol = locale.currencySymbol else {
return nil
}
return symbol
}
func sortAscByLength(list: [String]) -> [String] {
return list.sorted(by: { $0.count < $1.count })
}
Usage
let usd = getSymbolForCurrencyCode(code: "USD")
let jpy = getSymbolForCurrencyCode(code: "JPY")
let cny = getSymbolForCurrencyCode(code: "CNY")
let cad = getSymbolForCurrencyCode(code: "CAD")
let uah = getSymbolForCurrencyCode(code: "UAH")
let krw = getSymbolForCurrencyCode(code: "KRW")
let zar = getSymbolForCurrencyCode(code: "ZAR")
let chf = getSymbolForCurrencyCode(code: "CHF")
let all = [usd, jpy, cny, cad, uah, krw, zar, chf]
(lldb) po all
▿ 8 elements
- 0 : "$"
- 1 : "¥"
- 2 : "¥"
- 3 : "$"
- 4 : "₴"
- 5 : "₩"
- 6 : "R"
- 7 : "CHF"
Problems
Instinctively, I see that the one letter symbol approach can show an incorrect symbol if there are more than one distinct symbols for currency code, but I haven't seen such case.
Computing this each time is heavy lifting so when a user sets their currency setting, it's wise to store the computed result and use that result upon each lookup
The proper way to do this is to let the frameworks provide the information for you.
You can retrieve that information using an obscure class method on NSLocale called localeIdentifierFromComponents(). That method will take a dictionary that defines various attributes of your locale, and then returns an identifier you can use to actually construct an NSLocale instance. Once you have the NSLocale, you can ask it for its CurrencySymbol, like this:
let currencyCode = "CAD"
let localeComponents = [NSLocaleCurrencyCode: currencyCode]
let localeIdentifier = NSLocale.localeIdentifierFromComponents(localeComponents)
let locale = NSLocale(localeIdentifier: localeIdentifier)
let currencySymbol = locale.objectForKey(NSLocaleCurrencySymbol) as! String
// currencySymbol is "CA$"
I combined and improved all the suggestion here to have a drop-in(copy/paste) solution for the future readers(you).
It has its own local cache, case insensitive, and have an extension method to provide chaining for String. Swift 4/5 ready.
How to use:
"USD".currencySymbol //returns "$"
//OR
Currency.shared.findSymbol(currencyCode: "TRY") //returns "₺"
Tests:
XCTAssertEqual("$", "USD".currencySymbol)
XCTAssertEqual("₺", "TRY".currencySymbol)
XCTAssertEqual("€", "EUR".currencySymbol)
XCTAssertEqual("", "ASDF".currencySymbol)
Code:
class Currency {
static let shared: Currency = Currency()
private var cache: [String:String] = [:]
func findSymbol(currencyCode:String) -> String {
if let hit = cache[currencyCode] { return hit }
guard currencyCode.count < 4 else { return "" }
let symbol = findSymbolBy(currencyCode)
cache[currencyCode] = symbol
return symbol
}
private func findSymbolBy(_ currencyCode: String) -> String {
var candidates: [String] = []
let locales = NSLocale.availableLocaleIdentifiers
for localeId in locales {
guard let symbol = findSymbolBy(localeId, currencyCode) else { continue }
if symbol.count == 1 { return symbol }
candidates.append(symbol)
}
return candidates.sorted(by: { $0.count < $1.count }).first ?? ""
}
private func findSymbolBy(_ localeId: String, _ currencyCode: String) -> String? {
let locale = Locale(identifier: localeId)
return currencyCode.caseInsensitiveCompare(locale.currencyCode ?? "") == .orderedSame
? locale.currencySymbol : nil
}
}
extension String {
var currencySymbol: String { return Currency.shared.findSymbol(currencyCode: self) }
}
To simply get the currency symbol in Swift.
let locale = Locale.current // currency symbol from current location
//let locale = Locale(identifier: "fr_FR") // or you could specify the locale e.g fr_FR, en_US etc
let currencySymbol = locale.currencySymbol!
print("\(currencySymbol)")
SWIFT4
//converting USD to $a and GBP to £
viewDidLoad()
{
print(getSymbolForCurrencyCode(code: "USD")!) // prints $
print(getSymbolForCurrencyCode(code: "GBP")!) //prints £
}
func getSymbolForCurrencyCode(code: String) -> String?
{
let locale = NSLocale(localeIdentifier: code)
return locale.displayName(forKey: NSLocale.Key.currencySymbol, value: code)
}
I suggest a faster and more convenient solution.
You can get all possible symbols for a specific currency:
Currency.currency(for: "USD")! // Currency(code: "USD", symbols: ["US$", "USD", "$"])
Currency.currency(for: "CAD")! // Currency(code: "USD", symbols: ["$", "CA$"])
Or get the shortest symbol. This is usually what everyone wants:
Currency.currency(for: "CAD")!.shortestSymbol // "$"
Now about the speed. The first call to this method takes linear time proportional to the number of locales plus the number of codes. Each subsequent call for any code is executed in constant time. Therefore, if you are implementing a CurrencyPickerViewController or something similar, then this solution is optimal.
Also, this solution has one more plus. Since global constants and variables are always computed lazily, if you never call a method to get information about the currency, the cache will not take up any memory.
struct Currency {
/// Returns the currency code. For example USD or EUD
let code: String
/// Returns currency symbols. For example ["USD", "US$", "$"] for USD, ["RUB", "₽"] for RUB or ["₴", "UAH"] for UAH
let symbols: [String]
/// Returns shortest currency symbols. For example "$" for USD or "₽" for RUB
var shortestSymbol: String {
return symbols.min { $0.count < $1.count } ?? ""
}
/// Returns information about a currency by its code.
static func currency(for code: String) -> Currency? {
return cache[code]
}
// Global constants and variables are always computed lazily, in a similar manner to Lazy Stored Properties.
static fileprivate var cache: [String: Currency] = { () -> [String: Currency] in
var mapCurrencyCode2Symbols: [String: Set<String>] = [:]
let currencyCodes = Set(Locale.commonISOCurrencyCodes)
for localeId in Locale.availableIdentifiers {
let locale = Locale(identifier: localeId)
guard let currencyCode = locale.currencyCode, let currencySymbol = locale.currencySymbol else {
continue
}
if currencyCode.contains(currencyCode) {
mapCurrencyCode2Symbols[currencyCode, default: []].insert(currencySymbol)
}
}
var mapCurrencyCode2Currency: [String: Currency] = [:]
for (code, symbols) in mapCurrencyCode2Symbols {
mapCurrencyCode2Currency[code] = Currency(code: code, symbols: Array(symbols))
}
return mapCurrencyCode2Currency
}()
}
To see how this functionality works for all codes, you can use the code:
for code in Locale.commonISOCurrencyCodes {
guard let currency = Currency.currency(for: code) else {
// Three codes have no symbol. This is CUC, LSL and VEF
print("Missing symbols for code \(code)")
continue
}
print(currency)
}
An imperfect solution I found to get $ instead of US$ or CA$ was to attempt to match the user's current locale to the currency code first. This will work for situations where you're building a mobile app and an API is sending you currency code based on the settings in that user's account. For us the business case is that 99% of users have the same currency code set in their account on the backend (USD, CAD, EUR, etc.), where we're getting the information from, as they do on their mobile app where we're displaying currency the way a user would expect to see it (i.e. $50.56 instead of US$ 50.56).
Objective-C
- (NSLocale *)localeFromCurrencyCode:(NSString *)currencyCode {
NSLocale *locale = [NSLocale currentLocale];
if (![locale.currencyCode isEqualToString:currencyCode]) {
NSDictionary *localeInfo = #{NSLocaleCurrencyCode:currencyCode};
locale = [[NSLocale alloc] initWithLocaleIdentifier:[NSLocale localeIdentifierFromComponents:localeInfo]];
}
return locale;
}
Swift
func locale(from currencyCode: String) -> Locale {
var locale = Locale.current
if (locale.currencyCode != currencyCode) {
let identifier = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.currencyCode.rawValue: currencyCode])
locale = NSLocale(localeIdentifier: identifier) as Locale
}
return locale;
}
Swift 4 Version of Pancho's answer, As the String.characters is deprecated now.
We can simply apply dropLast() on String.
func getCurrencySymbol(from currencyCode: String) -> String? {
let locale = NSLocale(localeIdentifier: currencyCode)
if locale.displayName(forKey: .currencySymbol, value: currencyCode) == currencyCode {
let newlocale = NSLocale(localeIdentifier: currencyCode.dropLast() + "_en")
return newlocale.displayName(forKey: .currencySymbol, value: currencyCode)
}
return locale.displayName(forKey: .currencySymbol, value: currencyCode)
}
You can use static 'availableIdentifiers' collection, containing all posible identifiers as follows:
extension Locale {
static func locale(from currencyIdentifier: String) -> Locale? {
let allLocales = Locale.availableIdentifiers.map({ Locale.init(identifier: $0) })
return allLocales.filter({ $0.currencyCode == currencyIdentifier }).first
}
}
You can try this:
let formatter = NSNumberFormatter()
for locale in NSLocale.availableLocaleIdentifiers() {
formatter.locale = NSLocale(localeIdentifier: locale)
print("\(formatter.currencyCode) = \(formatter.currencySymbol)")
}
let countryCode = (Locale.current as NSLocale).object(forKey: .currencySymbol) as? String ?? "$"
Above will give current currency Symbol, For UK it gives me = £ Apple Doc
I'm trying to implement an asynchronous function as told in this topic but I always get the following error from Xcode : Type 'dispatch_queue_t!' does not conform to protocol 'OS_dispatch_queue'
Here's my code:
#IBAction func buyButton(sender: AnyObject) {
// get wanted symbol
let symbol = symbolField.text!
// get price of share
var priceShare :Double = 0
_ = lookup(symbol) { name, symbol, price in
dispatch_async(dispatch_get_main_queue()) {
priceShare = price
}
}
buy(symbol, number: 1, price: priceShare)
}
Here's the lookup function:
func lookup(entry : NSString, completion: ((name :String, symbol :String, price :String) -> Void)) {
// define return values
var name = String()
var symbol = String()
var price = String()
// define URL
let url = NSURL(string: "http://yahoojson.gobu.fr/symbol.php?symbol=\(entry)")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
name = jsonResult["name"] as! String
symbol = jsonResult["symbol"] as! String
price = jsonResult["price"]!!.stringValue as String
completion(name: name, symbol: symbol, price: price)
} catch {
print(error)
}
}
}
// run the task
task.resume()
}
Any hint on what I could be doing wrong?
I figure it out by myself. There was a bug inside on my code.
On the line
priceShare = price
I needed to put
priceShare = Double(price)!
since priceShare require a Double. Don't understand why Xcode didn't tell me so.
Swift 1.2 / Xcode 6.3.
Why is this valid:
class RangeDelegateNongeneric: NSObject, UIPickerViewDataSource {
var values = [Int]()
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return values.count
}
}
but this isn't:
class RangeDelegateGeneric<T>: NSObject, UIPickerViewDataSource {
var values = [T]()
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return values.count
}
}
Error: Type RangeDelegateGeneric<T> does not conform to protocol UIPickerViewDataSource
Even more oddly, the Fix-it message: Candidate is not #objc, but protocol requires it prepends #objc to the beginning of each function, but that doesn't Fix-it, and the Fix-it tool is happy to repeatedly prepend #objc!
This is fixed in Swift 2.0, specifically tested in Xcode 7 (beta 5 as of this writing).
99% sure this blog fragment explains it, although a more compiler-nerd-friendly explicit spec statement is bizarrely difficult to find:
https://developer.apple.com/swift/blog/?id=29
[Emphasis mine]
Swift-er SDKs: Swift 2 works even better with the Apple SDKs, thanks
in part to two new features in Objective-C: nullability annotations
and generics. The SDKs have been updated to annotate API that cannot
return nil so you don’t need to use optionals as often. And with a
true generics system employed by the SDKs you can more often preserve
detailed type information in your Swift 2 code.