2017-06-08 11 views
-4

私はそれぞれのスレッドを見ていますが、私の場合は解決策が見つかりません。 は私がモデルを持っている:文字列の値の種類は?メンバコンポーネントはありません。 (Struct)

import Foundation 

public struct Destinos: Data { 
    public var idDestino : Int? 
    public var desDestino : String? 

    public func dictionary() -> NSDictionary { 

     let dictionary = NSMutableDictionary() 

     dictionary.setValue(self.idDestino, forKey: "idDestino") 
     dictionary.setValue(self.desDestino, forKey: "desDestino") 

     return dictionary 
    } 
} 

だから私は後で使用してのtableViewでで表示するには、[文字列]にdesDestino「文字列」を変更したいです。このコードを別のファイルに書きます.swift:

var cadena = Destinos() 

cadena.desDestino = "HOLA, nada, algo, otra, cosa, mas que eso" 
let array = cadena.desDestino.components(separatedBy: ", ") // in this line i get the error: value type of string? has no member components. 

so ...問題は何ですか?

+4

「desDestino」は任意である。 'コンポーネント(seperatedBy:)'を呼び出す前に、それをアンラップする必要があります。 – Alexander

+1

ところで、 – Alexander

+2

には、はるかにきれいで、よりきれいで、より直感的な迅速な対応の代わりにNS *を使用している理由がありますが、 'コンポーネント(seperatedBy:)'が間違っていますか? – luk2302

答えて

1

ここにNSDictionaryを使用する理由はありません。ネイティブスウィフト辞書(リテラル付き)を使用してください。あなたの配列を生成するよう

public struct Destinos { 
    public let idDestino : Int? 
    public let desDestino : String? 

    public func toDictionary() -> [String: Any?] { 
     return [ 
      "idDestino": idDestino, 
      "desDestino": desDestino 
     ] 
    } 
} 

、次の2つの問題があります。 1. components(seperatedBy:)を 2. cadena.desDestinoつづりの間違っているアンラップされていない(またOptional<String>として知られている)String?です。これを処理する最も良い方法は、オプションの連鎖を使用して、が空の配列になるようにnil coalescence(??)を使用することです。nilです。

var cadena = Destinos(
    idDestino: 123, 
    desDestino: "HOLA, nada, algo, otra, cosa, mas que eso" 
) 

let array = cadena.desDestino?.components(separatedBy: ", ") ?? [] 
関連する問題