NSLocale Swift 3 [英] NSLocale Swift 3

查看:99
本文介绍了NSLocale Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift 3中获取货币符号?

How do I get the currency symbol in Swift 3?

public class Currency: NSObject {
    public let name: String
    public let code: String
    public var symbol: String {
        return NSLocale.currentLocale().displayNameForKey(NSLocaleCurrencySymbol, value: code) ?? ""
    }

    // MARK: NSObject

    public init(name: String, code: String) {
        self.name = name
        self.code = code
        super.init()
    }
}

我知道NSLocale被重命名为Locale,但是displayNameForKey被删除了,我似乎只能使用localizedString(forCurrencyCode:self.code)在当前语言环境中生成货币名称,而无法获取其符号.我正在寻找一种在当前语言环境中获取外币符号的方法.

I know NSLocale got renamed to Locale, but displayNameForKey got removed and I only seem to be able to use localizedString(forCurrencyCode: self.code) to generate the name of the currency in the current locale without being able to get its symbol. I'm looking for a way to get a foreign currency symbol in a current locale.

我是在俯视什么吗?

推荐答案

NSLocale未重命名,它仍然存在. Locale是一个 Swift 3中引入的新类型作为值类型包装器 (比较 SE-0069可变性和基础价值类型).

NSLocale was not renamed, it still exists. Locale is a new type introduced in Swift 3 as a value type wrapper (compare SE-0069 Mutability and Foundation Value Types).

显然Locale没有displayName(forKey:value:)方法, 但您始终可以将其转换为基金会的对应版本 NSLocale:

Apparently Locale has no displayName(forKey:value:) method, but you can always convert it to its Foundation counterpart NSLocale:

public var symbol: String {
    return (Locale.current as NSLocale).displayName(forKey: .currencySymbol, value: code) ?? ""
}

更多示例:

// Dollar symbol in the german locale:
let s1 = (Locale(identifier:"de") as NSLocale).displayName(forKey: .currencySymbol, value: "USD")!
print(s1) // $

// Dollar symbol in the italian locale:
let s2 = (Locale(identifier:"it") as NSLocale).displayName(forKey: .currencySymbol, value: "USD")!
print(s2) // US$

这篇关于NSLocale Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆