我正在阅读如何在Swift中编程,并且可选项的概念让我有点烦恼.对于为什么使用选项而言并不是真的,这是有道理的,但更多的是在什么情况下你不想使用选项.根据我的理解,一个可选项只允许将一个对象设置为nil,那你为什么不想要这个功能呢?是不是将对象设置为n告诉ARC释放对象的方式为零?并且基金会和Cocoa中的大部分功能都没有返回选项吗?因此,除了每次引用一个对象时都要输入一个额外的字符,有没有什么好的理由不使用可选代替常规类型?
我是java 8的新手并且学习lambda表达式.
我有一个界面.
Configuration.java
package com.raghu.example;
import java.util.Map;
public interface Configuration {
public Map<String,String> getPayload();
}
Run Code Online (Sandbox Code Playgroud)
Impl用于接口:ConfigurationImpl.java
package com.raghu.example;
import java.util.HashMap;
import java.util.Map;
public class ConfigurationImpl implements Configuration {
@Override
public Map<String, String> getPayload() {
Map<String,String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
//return null;
return map;
}
}
Run Code Online (Sandbox Code Playgroud)
我的主程序:Sample.java
package com.raghu.example;
import java.util.Optional;
public class Sample {
Configuration config;
/*
* if config is null, return "";
* if config.getPaylaod is null, return "";
* if config.payload is …Run Code Online (Sandbox Code Playgroud) 我是新来的.刚刚开始学习Swift,当我谈到可选项的主题时,我开始想知道未初始化变量的默认值是什么.
在Java中,'int'被初始化为0.在C中,它获得垃圾值.那么Swift是什么?为了更精确一点,当我写"var x:Int"时,存储在x中的是什么?
另外,如果未初始化的对象"var c:UIColor"不能指向nil,它指向什么?
我怎样才能转换List成Optional<List>?
以下代码生成编译错误:
public Collection<Optional<UserMeal>> getAll() {
Comparator comparator = new SortedByDate();
List<UserMeal> mealList = new ArrayList<>(repository.values());
Collections.sort(mealList,comparator);
Collections.reverse(mealList);
**List<Optional<UserMeal>> resultList = Optional.of(mealList);**
return resultList;
}
Run Code Online (Sandbox Code Playgroud) 我要求用户输入(这工作)并尝试输出不同的结果取决于输入是nil,空字符串,还是使用switch子句的非空字符串(不起作用).
第一次尝试给我一个错误,因为我试图将可选字符串与非可选字符串进行比较:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
switch userInput {
case nil, "": // Error: (!) Expression pattern of type ‘String’ cannot match values of type ‘String?’
print("You didn’t enter anything.")
default:
print("You entered: \(userInput)")
}
Run Code Online (Sandbox Code Playgroud)
很公平,所以我创建一个可选的空字符串来比较:
import Foundation
print("Hi, please enter a text:")
let userInput = readLine(stripNewline: true)
let emptyString: String? = "" // The new optional String
switch userInput {
case nil, emptyString: // Error: (!) Expression …Run Code Online (Sandbox Code Playgroud) 我正在开发一个程序,它使用返回的方法,Optional我需要迭代它并创建一个新对象.我怎么做?
import java.util.Optional;
class Info {
String name;
String profileId;
Info(String name, String profileId) {
this.name = name;
this.profileId = profileId;
}
}
class Profile {
String profileId;
String profileName;
Profile(String profileId, String profileName) {
this.profileId = profileId;
this.profileName = profileName;
}
}
class Content {
String infoName;
String profileName;
Content(String infoName, String profileName) {
this.infoName = infoName;
this.profileName = profileName;
}
public java.lang.String toString() {
return "Content{" + "infoName='" + infoName + '\'' + ", profileName='" + …Run Code Online (Sandbox Code Playgroud) 我有这个方法,我想返回一个空的可选项是没有找到
@Override
public Optional<Menu> findBySymbol (String symbol) {
Optional<Menu> menu =
StreamSupport
.stream(cachedMenus.get(ALL_CURRENCIES_KEY).spliterator(), true)
.findFirst();
return menu.orElse(Optional.empty());
}
Run Code Online (Sandbox Code Playgroud)
但是我收到了编译错误: Type mismatch: cannot convert from Optional<Object> to Menu
这个
NSAttributedString.Key.foregroundColor: view.tintColor
Run Code Online (Sandbox Code Playgroud)
触发此警告
NSAttributedString.Key.foregroundColor: view.tintColor
Run Code Online (Sandbox Code Playgroud)
但是警告不应该是
Expression implicitly coerced from 'UIColor?' to 'Any'
Run Code Online (Sandbox Code Playgroud)
由于这个财产
NSAttributedString.Key.foregroundColor
Run Code Online (Sandbox Code Playgroud)
是类型UIColor?
注:这只是开始更新后发生在斯威夫特5,Xcode的10.2。
这里是更多上下文:
override func viewDidLoad() {
super.viewDidLoad()
UIBarButtonItem.appearance().setTitleTextAttributes(
[
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 40),
NSAttributedString.Key.foregroundColor: view.tintColor
], for: .normal)
}
Run Code Online (Sandbox Code Playgroud) 我目前正在学习Scala,遇到了两种处理选项的方法。结果是相同的,但我想知道使用一个相对于另一个是否有优势(或者是否有更好的选择)。
如果输入也可以除以4,则divByTwo1和divByTwo2函数将返回输入除以2,否则将返回None。
def divByFour(i: Int): Option[Int] = {
if (i % 4 == 0) {
Some(i / 4)
} else {
None
}
}
def divByTwo1(i: Int): Option[Int] = {
for {
fourth <- divByFour(i)
} yield fourth * 2
}
def divByTwo2(i: Int): Option[Int] = {
divByFour(i) match {
case Some(fourth) => Some(fourth * 2)
case None => None
}
}
Run Code Online (Sandbox Code Playgroud) monads functional-programming scala pattern-matching optional
在以下代码段中,我的Foo类带有始终返回的相同实例的方法Optional。然后我有另一个OneMoreClass使用Foo类的类。
您可以从源代码中看到调用get()方法是安全的,method1因为始终在中检查该方法method2。
IntelliJ IDEA仍然显示警告的问题(您只需将此代码段复制到IDEA,您将看到此问题)。
public class Example {
public static class Foo {
private final Optional<String> value = Optional.empty();
public Optional<String> bar() {
return value;
}
}
public static class OneMoreClass {
void method1(final Foo foo) {
method2(foo);
System.out.println(foo.bar().get()); // here the warning is shown in IntelliJ IDEA:
// "Optional.get()" without "isPresent()" check
}
void method2(final Foo foo) {
if (!foo.bar().isPresent()) {
throw new IllegalArgumentException("No value"); …Run Code Online (Sandbox Code Playgroud)