标签: optional

Swift:可选下标的可选链接

我有一个let map : [String: String]和一个let key: String?

什么是最简洁的访问方式map[key]String?如果我有一个keyNone如果没有,则返回一个)?

optional swift

0
推荐指数
1
解决办法
318
查看次数

如何使用 OR 子句在 Swift 中过滤数组

我试图通过匹配用户名或全名来过滤 Swift 中的一组对象。

   filteredRegUserArray = regUserArray.filter {
                $0.userName.lowercaseString.hasPrefix(lowercasePrefix) || 
                $0.fullName.lowercaseString.hasPrefix(lowercasePrefix)}
Run Code Online (Sandbox Code Playgroud)

arrays filter optional swift

0
推荐指数
1
解决办法
1005
查看次数

条件绑定的初始值设定项必须具有 Optional 类型,而不是“Date”

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)

xcode core-data optional ios swift

0
推荐指数
1
解决办法
3352
查看次数

如何安全地解开我从 Firebase 中的数据库调用的这个可选 URL?

这是屏幕截图,您可以看到它显示错误,因为我强制解包并且一些 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)

url optional ios firebase swift

0
推荐指数
1
解决办法
3020
查看次数

Swift 4:将 Bool 选项打印为未包装的 true 或 false 或包装的 nil?

基本上我想将以下值打印为“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 文件,了解此值是真还是假或尚未检查很有用。

boolean optional swift swift4

0
推荐指数
1
解决办法
952
查看次数

三元展开迅速

在 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)

但两者都给出错误。知道我该如何解决这个问题吗?

ternary-operator optional ios swift unwrap

0
推荐指数
1
解决办法
582
查看次数

从 Java Stream 生成的 Optional 中消除额外的 isPresent() 调用

我是一个相对新手的 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)

java optional

0
推荐指数
1
解决办法
69
查看次数

How do I use Option::or with references to Options?

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?

reference optional rust

0
推荐指数
1
解决办法
64
查看次数

如何停止使用 Optional IsPresent() 乱扔代码?

所以我完全使用 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

java coding-style code-cleanup optional

0
推荐指数
1
解决办法
64
查看次数

如何转换选项中的内部值?

我有一个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)

我是新来的锈和不完全获得时使用的复杂性matchif let或时使用的?运营商。

我的实现是 Rust 惯用的吗?对我来说似乎比较冗长,而且看起来像一个到处都会出现的模式,所以我可以想象这可以更简洁地处理;是这样吗?

optional rust rust-2018

0
推荐指数
1
解决办法
598
查看次数