質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

Q&A

解決済

4回答

3226閲覧

Swift2で、テキストファイルの開き方がわからない

Nicola

総合スコア21

Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

0グッド

0クリップ

投稿2015/08/01 03:53

編集2015/08/05 08:06

以下のコードでlet data = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)がエラーになります。

import Cocoa
import Foundation

class ViewController: NSViewController {

override func viewDidLoad() { super.viewDidLoad() let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let filePath = paths[0].stringByAppendingPathComponent("dictionary00.txt") let data = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) data.enumerateLines { (line, stop) -> () in println(line) println(split(line,{ $0 == "\t"})) } // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } }

}

正しい開き方を教えていただけないでしょうか。
よろしくお願いします。

解決しました。

下記のコードが最終コードとなります。

import Cocoa
import Foundation
extension String : CollectionType {}

class ViewController: NSViewController {

override func viewDidLoad() { super.viewDidLoad() let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let filePath = paths[0].stringByAppendingPathComponent("test01.txt") print (filePath) let data = htmlStringWithFilePath(filePath) data!.enumerateLines { (line, stop) -> () in print(line) print(split(line){ $0 == "\t"}) } // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } private func htmlStringWithFilePath(path: String) -> String? { do { let data = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding) return data } catch { print("Lookup error: no HTML file found for path, \(path)") return nil } }

}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Stripe

2015/08/01 09:49

質問文を編集して、ViewControllerのコードを丸ごと貼り付けてください。
guest

回答4

0

ベストアンサー

swift2 = Xcode7 beta 何ですね…
Xcode6.3 (= swift1.2)で確認していました <(_ _)>

swiht2になってエラーハンドリングのやり方が変わったそうで、下記サイトに実装例が載っていました。(環境が無いので未確認ですが)

http://stackoverflow.com/questions/31159291/xcode-7-beta-gives-error

今度こそ解決すると良いのですが・・・

投稿2015/08/05 04:27

pi-chan

総合スコア5936

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Nicola

2015/08/05 06:58

ありがとうございます。基本部分は解決いたしました。 後一つの部分だけ、エラーが出てしまいます。 コードを以下に記します。 override func viewDidLoad() { super.viewDidLoad() let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let filePath = paths[0].stringByAppendingPathComponent("test01.txt") print (filePath) let data = htmlStringWithFilePath(filePath) data!.enumerateLines { (line, stop) -> () in print(line) println(split(line){ $0 == "\t"}) } // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } private func htmlStringWithFilePath(path: String) -> String? { // Get HTML string from path // you can also use String but in both cases the initializer throws // so you need the do-try-catch syntax do { // use "try" let data = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding) // or directly return return data // Check for error } catch { // an "error" variable is automatically created for you // in Swift 2 print is now used instead of println. // If you don't want a new line after the print, call: print("something", appendNewLine: false) print("Lookup error: no HTML file found for path, \(path)") return nil } } 上記のタブ区切りがうまくいきません。 print(split(line){ $0 == "\t"}) もしくは println(split(line){ $0 == "\t"}) splitでエラーになってしまいます。 わかりましたら、お力添え頂ければ助かります。 よろしくお願いいたします。
Nicola

2015/08/05 07:01

エラー名は Cannot invoke 'split' with an argument list of type '(String, (String) -> Bool)' です。
pi-chan

2015/08/05 07:57

解決に向かっているようで少し安心しました。 しかし、swift2 の仕様変更は結構激しいですね… どうやら String が Sliceable でなくなったとかで、下記に③通りの解決策が提案されていました。 http://stackoverflow.com/questions/30759158/using-the-split-function-in-swift-2 現在のコードに一番近いのは No.3 でしょうか? 解決することを祈っております。
Nicola

2015/08/05 08:07

ありがとうございます。No.3のコードでいけました。 色々ご援助いただきありがとうございました。
guest

0

入力ファイルが下記パスに存在しTSV(TAB区切り)になっているという前提で、動作確認しました。

/Users/{ユーザー}/Documents/dictionary00.txt

swift

1import Foundation 2 3let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 4let filePath = paths[0].stringByAppendingPathComponent("dictionary00.txt") 5let data = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) as! String 6data.enumerateLines { (line, stop) -> () in 7 println(line) 8 println(split(line){ $0 == "\t"}) 9}

今更な確認ですが・・・Mac上での開発には Xcode をご使用になられていますか??

推測なので間違っていたら申し訳ありませんが、きっとネット上の情報(実装例)をご参考にスクリプトを作成されているのだと思います。
が、Nicolaさんがご参考にされたのは、同じswift のコードでも ios (モバイル)用であり OS X (Mac)用ではありません。

今度は次の行がエラー

と仰っている箇所については、先に回答した通り末尾に as! String を付加してダウンキャストすればOKのはずです。

さらに、split の使い方が少し違っていたようです。。

老婆心ながら一言。
先を急ぐお気持ちは十分に分かりますし、実際に確認しながら進めるのも非常に重要なことなのですが、まずは アプリの骨組み と、開発ツールである Xcode の基本的な使い方くらいはしっかりと確認してからコーディングを進められた方が結果的には早いと思います。
急がば回れ、ということです。

投稿2015/08/04 17:46

pi-chan

総合スコア5936

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Nicola

2015/08/05 02:25 編集

as! Stringでダウンキャストもしているんですが・・・ NSStringでエラーになってしまいます。 Cannot find an initializer for type 'NSString' that accepts an argument list of type '(contentsOfFile: String, encoding: UInt, error: nil)' 一応、OS X用にXCODE7を設定しているんですが。 確かにアプリの骨組みは、ある程度のものが頭にあるだけですが。 10年前までVB6での開発が最後でしたが。その後は、HP開発の言語を少ししたくらいです。
pi-chan

2015/08/05 04:19

ゴメンナサイ、初学者故に根本的に思い違いをしていました。。 新たな回答を別途記載致しますので、ご確認をお願い致します。
guest

0

そのテキストファイルを開くコードを、関数(メソッド)の中に書いてください。

投稿2015/08/02 02:51

Stripe

総合スコア2183

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Nicola

2015/08/02 03:04

開く前に、ディレトリ設定でエラーなんですが…
Stripe

2015/08/02 03:39

だから、そのコードを関数の外側に書いているからエラーになるのです。
Nicola

2015/08/02 23:49

ありがとうございます
guest

0

swift初学者なので間違っていたらゴメンなさい。
自分の環境で試してみたところ以下のように修正すればOKのようです。

誤)let data = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)
正)let data = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) as! String

デバッガーで「型」を調べてみると分かりますが、
NSString → Swift.Optional<NSString>
なので、 as! String でダウンキャストして
data → Swift.String
としてやらないと、enumerateLines メソッドを利用できないということのようです。

投稿2015/08/02 00:45

pi-chan

総合スコア5936

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Nicola

2015/08/02 00:56

ありがとうございます。 しかしその上の行の let filePath = paths[0].stringByAppendingPathComponent("dictionary00.txt") のpaths[0]ですでに、エラーになっています。
pi-chan

2015/08/02 07:57

失礼しました、あまり良く見ていませんでした。。 Stripeさんが回答されている通り、処理全体を、たとえば「viewDidLoad」関数の中に書いてください。 自分は、テスト用のボタンをクリックした時に動作するよう、自分で追加した関数の中に当該のコードを記載していたため、paths[0]のところではエラーになっていませんでした。。
Nicola

2015/08/02 23:48

ありがとうございます。今度は次の行がエラーになってしまいました。
pi-chan

2015/08/03 06:02

おかしいですね… 自分の環境ではエラーなく読み込み完了しますが。 2点確認ですが ①ご使用のswiftのバージョンは? ②対象のフォルダに読み込み可能なファイルが間違いなく配置されていますか?配置先フォルダを探すのちょっと面倒だと思いますが~
Nicola

2015/08/03 06:49 編集

①2.0Bata ②配置の確認はしました。/Users/*****/Documents/dictionary00.txt エラーは Cannot find an Initializer for type NSString that accepts an argument list of type (contentsOfFile: String,encoding: Uint, error: nil) です。 よろしくお願いします。
pi-chan

2015/08/03 10:36

現在、出先なので詳しくコメントしにくいのですが~ 今はios向けアプリをmac上でシミュレーターを使って開発中なのでは? もしそうなら②が違うと思います。 下記を参考に正しいパスにファイルを置いてからテストして下さい。 >http://qiita.com/singo405/items/b84f81ee2daaef27d0a2
Nicola

2015/08/04 05:44

ありがとうございます。 一応mac用の変換ソフトを作っています。 タブ区切りテキストを読んで、データベースに書き込むことをしようとしています。 しかし、上記のエラーになってしまいます。 よろしくお願いします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問