Skip to content

Instantly share code, notes, and snippets.

@yamamotoj
Created February 12, 2015 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamamotoj/5b6e14f4566d1446dffb to your computer and use it in GitHub Desktop.
Save yamamotoj/5b6e14f4566d1446dffb to your computer and use it in GitHub Desktop.
Swift 1.2のif let複数宣言と例外処理 ref: http://qiita.com/boohbah/items/84e9d76a8ceaf9f56077
func getA()->String?{
return "A"
}
func getB()->String? {
return "B"
}
func getC()->String?{
return "C"
}
func test() -> (){
// カンマ区切りで複数の変数のOptional判定 + 宣言が可能に
if let a = getA(), b = getB(), c = getC(){
print( a + b + c + "のすべてがnilではない ")
}else{
print( "a,b,cのうちどれかがnilの場合はfalse")
}
}
func getA()->String?{
return "A"
}
func getB(a:String)->String? {
return a + "B"
}
func getC(b:String)->String?{
return b + "C"
}
func test() -> (){
if let a = getA(),
b = getB(a), // ←直前に解決したaを引数として使用
c = getC(b) // ←直前に解決したbを引数として使用
{
print( a + b + c + "のすべてがnilではない ")
}else{
print( "a,b,cのうちどれかがnilの場合はfalse")
}
}
func test() -> (){
if let a = getA(){
if let b = getB(a) {
if let c = getC(b) {
print( a + b + c + "のすべてがnilではない ")
return
}
}
}
print( "a,b,cのうちどれかがnilの場合はfalse")
}
簡単な制御用関数
// if letのなかではOptional型しか扱えないので、
// 通常の変数を扱うためにOptional型でくるんでやる
func let_<T>(s:T) -> T?{
return s
}
// if文に相当する分岐
func if_<T>(b:Bool, #then:()->T, #els:()->T) -> T{
if b {
return then()
}else{
return els()
}
}
// あとはfor文に相当する処理とか
func getC(c:String) -> String? {
return c + "C"
}
func test(arg:String) -> String? {
if let
a = let_(arg), // 引数をoptional化
b = if_(a == "A", // 条件分岐
then:{
return a + "B"
},els:{
return nil
}),
c = getC(b)
{
return c
}
return nil
}
test("A") // => "ABC"
test("B") // => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment