ryohei ryohei - 3 years ago 198
iOS Question

Swift3: How to use user default data in NSArray?

I have created a user default property called "data", which holds values of

, meaning it is an array of String. And I want to use Strings in the "data" as
written below
("one", "two", "three")
. I have created a method;

func getInput() -> [String] {
if let myData = userDefaults.array(forKey: "data") as? [String] {
return myData
return []

And I put the code inside
, which looked like inside
. However, an error came out, saying something like it is not NSArray, so I think it is the problem.

func textViewDidChange(_ textView: UITextView) {
let attrStr = NSMutableAttributedString(string: mytextView.text)
let inputLength = attrStr.string.characters.count
let searchString : NSArray = NSArray.init("one", "two", "three")
for i in 0...searchString.count-1 {
let string : String = searchString.object(at: i) as! String
let searchLength = string.characters.count
var range = NSRange(location: 0, length: attrStr.length)
while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: string, options: [], range: range)
if (range.location != NSNotFound) {
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
mytextView.attributedText = attrStr

Also if there is a better way to save data from users rather than user defaults, could you tell me why and sample too. But my main issue is how to access user default saved data and put the data into the

Answer Source

In Swift it is batter if you use Swift native Array and Dictionary instead of NSArray and NSDictionary, but to answer your question you can initialize NSArray with Swift type Array using initializer NSArray(array:).

let searchString : NSArray = NSArray.init(array: getInput())


let searchString : NSArray = NSArray(array: getInput())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download