在Swift中,有没有办法检查数组中是否存在索引而没有抛出致命错误?
我希望我能做到这样的事情:
let arr: [String] = ["foo", "bar"]
let str: String? = arr[1]
if let str2 = arr[2] as String? {
// this wouldn't run
println(str2)
} else {
// this would be run
}
Run Code Online (Sandbox Code Playgroud)
但我明白了
致命错误:数组索引超出范围
我在弹性搜索中存储类似以下信息:
{ "timeslot_start_at" : "2013-02-01", "timeslot_end_at" : "2013-02-03" }
Run Code Online (Sandbox Code Playgroud)
鉴于我有另一个日期范围(例如从用户输入给出),我想要搜索相交的时间范围.与此类似:确定两个日期范围重叠是否概述了以下逻辑是我所追求的:
(StartDate1 <= EndDate2) and (StartDate2 <= EndDate1)
Run Code Online (Sandbox Code Playgroud)
但我不确定如何将其纳入弹性搜索查询,我是否会使用范围过滤器并仅设置"到"值,将空白留空?或者有更有效的方法吗?
我setBackButtonTitlePositionAdjustment:forBarMetrics:在 UIBarButtonItem 的外观上使用该方法,如下所示:
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(12, -1), forBarMetrics: .Default)
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(15, -1), forBarMetrics: .Compact)
Run Code Online (Sandbox Code Playgroud)
然后,在视图控制器中我想用来backButtonTitlePositionAdjustment(for:)获取该值。我假设必须有一个我可以使用的 UIBarMetrics 值 - 也许在导航栏或 UITraitCollection 中,但我认为我错过了一些明显的东西?
我正在尝试根据字典中的值设置类的一些属性,目前我这样做:
let view: UIView = UIView()
if let hidden: Bool = self.props["hidden"] as? Bool {
view.hidden = hidden
}
if let frame: CGRect = self.props["frame"] as? CGRect {
self.uiInstance?.frame = frame
}
if let backgroundColor: UIColor = self.props["backgroundColor"] as? UIColor {
self.uiInstance?.backgroundColor = backgroundColor
}
Run Code Online (Sandbox Code Playgroud)
这对于一些属性来说很好,但是当涉及到大量的属性时会很烦人.是否可以在swift中执行以下操作:
var view: UIView = UIView()
let config: Dictionary<String, Any?> = ["frame": CGRectZero, "backgroundColor": UIColor.whiteColor()]
for (key, value) in config {
// view.??? = value
}
Run Code Online (Sandbox Code Playgroud)
我知道如果config字典的内容与UIView实例上的属性不匹配,则可能存在错误风险.例如["text": "this is not going to …
我试图在我的部分文件中使用一个变量,但它似乎不是从它的父模板继承的。
例如:
指数液体
{% assign foo = "bar" %}
{% section 'example' %}
Run Code Online (Sandbox Code Playgroud)
部分/示例.液体
<h1>{{ foo }}</h1>
{% schema %}
{
"name": "Example",
"settings": [
...
]
}
{% endschema %}
Run Code Online (Sandbox Code Playgroud)
它不会输出 的值{{ foo }},而我只是得到:<h1></h1>好像变量从未定义过一样。
我认为部分会像片段一样工作,其中父模板中定义的任何内容都在包含的片段中:
指数液体
{% assign foo = "bar" %}
{% include 'example' %}
Run Code Online (Sandbox Code Playgroud)
片段/example.liquid
<h1>{{ foo }}</h1>
Run Code Online (Sandbox Code Playgroud)
<h1>bar</h1>渲染时我会得到的地方。
谢谢!