2016-05-12 1 views
1

ボタンを押すとsplitLatを作成します:splitLatitudeというスローイング関数からcurrentLocation:CLLocationCoordinate2D?を取得します。これはdo {} catch {}の外で変数/定数を使用する-swift2

「扱いされていませんここからスローエラー」エラーが表示されます

@IBAction func ButtonPress() { 
     let splitLat = try self.splitLatitude(self.currentLocation) 
     LatSplitLabel.text = "\(splitLat)" 
} 

私はその後、ラベルとしてsplitLatを使用したい(そのが、他のもののために使用されることになるが、これは例を提供しています)私は、DO catchブロック

do{ 
     let splitLat = try self.splitLatitude(self.currentLocation) 
    } catch { 
     print("error") //Example - Fix 
    } 

が、それを置くことによってこの問題を解決する私はsplitLatは「未解決識別子」迅速に

新があるのラベル後で設定しようとすると、私は何か基本的なものを見逃していますか?私は間違った理解を持っていますか? Do文の外でdo {}文から定数を使用する方法があります。試行されたリターンが、機能のために予約されています。

は本当に

おかげ

答えて

2

次の2つのオプション(私はsplitLatStringタイプだと仮定します)

do{ 
    let splitLat = try self.splitLatitude(self.currentLocation) 
    //do rest of the code here 
} catch { 
    print("error") //Example - Fix 
} 

2番目のオプションを持っているが、変数

let splitLat : String? //you can late init let vars from swift 1.2 
do{ 
    splitLat = try self.splitLatitude(self.currentLocation) 
} catch { 
    print("error") //Example - Fix 
} 
//Here splitLat is recognized 
を先行宣言任意の助けに感謝します

今、プロの説明傷み。 Swiftで (および他の多くの言語)変数は彼らだけが

範囲はあなたが後に実行を成功したいなら、これはスコープエラーです{/* scope code */ }

{ 
    var x : Int 

    { 
     //Here x is defined, it is inside the parent scope 
     var y : Int 
    } 
    //Here Y is not defined, it is outside it's scope 
} 
//here X is outside the scope, undefined 
+0

ありがとうございました!これを理解できるはずです。オプション1を考えていたのですが、それは私の目的のためには機能しませんでしたが、オプション2は完璧です。ありがとう! –

0

これらのブラケットの間に定義されて定義されてい範囲内で定義されていますdo/catchブロック。 do/catchの実行後にこの変数を利用するには、このdo/catchスコープの外側で変数を宣言する必要があります。

このお試しください:ここで

var splitLat: <initialType> = <initialValue> 
do { 
    let splitLat = try self.splitLatitude(self.currentLocation) 
} catch { 
    print("error") 
} 

print(splitLat) 

スイフト2.2遊び場で実行でっち上げ例です。

enum Errors: ErrorType { 
    case SomeBadError 
} 

func getResult(param: String) throws -> Bool { 
    if param == "" { 
     throw Errors.SomeBadError 
    } 
    return true 
} 

var result = false 
do { 
    result = try getResult("it") 
} catch { 
    print("Some error") 
} 

print(result) 
関連する問題