我有一个let map : [String: String]和一个let key: String?。
什么是最简洁的访问方式map[key](String?如果我有一个key,None如果没有,则返回一个)?
我试图通过匹配用户名或全名来过滤 Swift 中的一组对象。
filteredRegUserArray = regUserArray.filter {
$0.userName.lowercaseString.hasPrefix(lowercasePrefix) ||
$0.fullName.lowercaseString.hasPrefix(lowercasePrefix)}
Run Code Online (Sandbox Code Playgroud) Xcode 大喊错误
但我不知道会发生什么。我一直在寻找,我认为这可能与铸造和可选有关。第一个给出条件绑定的初始化器必须具有可选类型,而不是“日期”,第二个和第三个给出条件绑定的初始化器必须具有可选类型,而不是“双”
for article in (topic.articleArrays ?? nil)!{
if let articleId = article.id,
let articleHeadline = article.headline,
let articleSummary = article.summary,
let articleCity = article.city,
let articleState = article.state,
let articleDateretrieved = article.dateRetrieved,
let articlePublisher = article.publisher,
let articleLatitude = article.latitude,
let articleLongitude = article.longitude,
let articleRawBaseUrl = article.rawBaseUrl,
let articleRawUrl = article.rawUrl {
editedArticles?.append(NewsArticle(id: articleId, headline: articleHeadline, publisher: articlePublisher, summary: articleSummary, rawUrl: articleRawUrl, rawBaseUrl: articleRawBaseUrl, retrieved_date: articleDateretrieved, city: articleCity, state: articleState, latitude: articleLatitude, longitude: articleLongitude)) …Run Code Online (Sandbox Code Playgroud) 这是屏幕截图,您可以看到它显示错误,因为我强制解包并且一些 url 为空:

我怎样才能安全地解开这个 URL,这样我就不必强制解包了?
代码:
func tableView (_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int
{
return players.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
Reusable.reuseIdForMain) as! CustomCell
cell.nameLabel.text = players[indexPath.row].name
cell.otherInfo.text = players[indexPath.row].otherInfo
if let url = players[indexPath.row].imageUrl{
cell.profileImage.load.request(with: URL(string:url)!)
}
return cell
}
Run Code Online (Sandbox Code Playgroud) 基本上我想将以下值打印为“true”、“false”或“nil”。如果我尝试仅使用包装的值,我会得到我想要的“nil”,但会获得不需要的“Optional(true)”或“Optional(false)。如果我强制解开该值并且值为 nil,则会出现致命错误。我尝试了下面的代码,因为我已经看到它适用于字符串,但是因为“nil”不是 Bool 类型,所以它不被接受。有什么解决方案吗?
var isReal: Bool?
String("Value is \(isReal ?? "nil")")
Run Code Online (Sandbox Code Playgroud)
我正在导出到 csv 文件,了解此值是真还是假或尚未检查很有用。
在 swift 我使用这个代码:
var categories: Results<Category>? //Realm dataType
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let categories = categories, !categories.isEmpty {
return categories.count
} else {
return 1
}
}
Run Code Online (Sandbox Code Playgroud)
我现在希望将 tableView 的代码构建为三元运算符,但不知道如何执行此操作。我找到了以下页面:https : //dev.to/danielinoa_/ternary-unwrapping-in-swift-903但我仍然不清楚。
我试过的是:
return categories?.isEmpty ?? {($0).count} | 1
Run Code Online (Sandbox Code Playgroud)
或者
let result = categories?.isEmpty ?? {($0).count} | 1
return result
Run Code Online (Sandbox Code Playgroud)
但两者都给出错误。知道我该如何解决这个问题吗?
我是一个相对新手的 Stream 用户,我觉得应该有一种更简洁的方法来完成我下面的操作。是否可以在单个 Stream 中完成以下代码的全部操作(消除底部的 if/else)?
谢谢!
Optional<SomeMapping> mapping = allMappings.stream()
.filter(m -> category.toUpperCase().trim().equalsIgnoreCase(m.getCategory().toUpperCase().trim()))
.findAny();
if (mapping.isPresent()) {
return mapping.get();
} else {
throw new SomeException("No mapping found for category \"" + category + "\.");
}
Run Code Online (Sandbox Code Playgroud) I have the following:
fn foo(f: &Option<Huge>) {}
fn bar(a: &Option<Huge>, b: &Option<Huge>) {
foo(a.or(b));
}
Run Code Online (Sandbox Code Playgroud)
Huge is some big struct that I don't want to copy or clone. This does not work because .or() takes a and b by value.
Is there an easy solution? I can probably do something like this:
foo(if a.is_some() { a } else { b });
Run Code Online (Sandbox Code Playgroud)
Surely there is a better way?
所以我完全使用 isPresent 而不是使用 == null 来检查对象是否成功返回,但我觉得我陷入了用 isPresent 乱丢代码的坑。
所以假设我有一堆不同的端点来检索或更新模型。我希望在他们每个人的开头都没有 isPresent 检查这个对象是否存在!
例子:
Optional<Object> myObject = objectRegistry.get(name);
if (myObject.isPresent()) {
doSomething();
} else {
throw new ObjectNotFoundException(stampName);
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找解决这种乱扔垃圾的最佳实践,我可以想象其中一种解决方案是使用一种方法来执行此检查,并且我可以随时调用它,而调用它的其他方法将不得不抛出 ObjectNotFoundException
我有一个Option包含一些 JSON 的。如果是Some,则必须转换内部 JSON,但如果是None,则必须保留None。
这就是我目前实施的方式:
struct One;
struct Other;
impl One {
pub fn convert(&self) -> Other {
Other {}
}
}
fn example(attr: Option<One>) -> Option<Other> {
match attr {
Some(attr) => Some(attr.convert()),
None => None,
}
}
Run Code Online (Sandbox Code Playgroud)
我是新来的锈和不完全获得时使用的复杂性match,if let或时使用的?运营商。
我的实现是 Rust 惯用的吗?对我来说似乎比较冗长,而且看起来像一个到处都会出现的模式,所以我可以想象这可以更简洁地处理;是这样吗?