Skip to main content

Mapbox の Exp 関連の tips

Exp(.startsWith) は SwiftUI では非対応

やりたいこと

こう書きたいが、SwiftUI 版では .startsWith 対応していないらしい

swift
Exp(.startsWith) {
Exp(.get) { "cityName" }
Exp(.literal) { selectedCityName }
}

代替の方法

ゴリッと書けば良い(マッチさせたい文字数で切って比較すれば良い)

swift
Exp(.eq) { // startsWith
Exp(.slice) {
Exp(.toString) { Exp(.get) { "cityName" } }
0
selectedCityName.count
}
Exp(.literal) { selectedCityName }
}

条件によって Exp 追加したい

やりたいこと

swift
var filterCondition: Exp {
Exp(.all) {
Exp(.eq) {
Exp(.get) { "isAvailable" }
Exp(.literal) { true }
}
if selectedCityName != "" { // ★ こうは書けない
Exp(.eq) {
Exp(.get) { "cityName" }
Exp(.literal) { selectedCityName }
}
}
}
}

解決方法

swift
func all(_ exps: [Exp]) -> Exp { // ★ ヘルパーを作っておく
exps.dropFirst().reduce(exps.first!) { partial, next in
Exp(.all) {
partial
next
}
}
}

var filterCondition: Exp {
var conditions: [Exp] = []

conditions.append(
Exp(.eq) {
Exp(.get) { "isAvailable" }
Exp(.literal) { true }
}
)

if selectedCityName != "" {
conditions.append(
Exp(.eq) {
Exp(.get) { "cityName" }
Exp(.literal) { selectedCityName }
}
)
}
return all(conditions) // 配列から Exp にする
}