swift - delete or replace <null> values from nested dictionary

swift string remove range
swift string remove prefix
swift remove characters from string
swift string remove suffix
swift remove character set from string
remove all special characters from string swift 4
swift remove last character from string
swift remove multiple characters from string

I have some data from server, and I'm using Alamofire SwiftyJSON to convert it to [String: Any]. Then I'm saving it to plist using SwiftyPlistManager. The point is that SwiftyPlistManager crashed when saving <null>, so I need to replace all <null>or nilto "".

My Dictionary after Alamofire SwiftyJSON looks this way:

["info_editable": true,
 "name": Android Q,
 "is_message": true,
 "images": [["id": 92,
             "image": /media/product/102.png]],
 "video_description": <null>,
 "is_valid": true]

or it could be -

["info_editable": true,
 "name": Android Q,
 "is_message": true,
 "images": <null>,
 "video_description": <null>,
 "is_valid": true]

I suppose to use Codable from raw data, but have no idea how to set initial value as empty string or [[]], then check if parced data is <null> and leave initial value as default. Or is there any way to list nested dictionary to replace <null>to ""?

You can try

var dic = ["1":nil,"2":"33","3":"5444"]
let res = dic.mapValues { $0 == nil ? "" : $0 }
print(res) // ["1": Optional(""), "2": Optional("33"), "3": Optional("5444")]

remove(at:), Swift Standard Library The position of the character to remove. i must be a valid index of the string that is not equal Replaces this string with the empty string. swift goes out of its way to use different terminology for almost everything. almost any other languages it's just replace – javadba May 27 at 21:05 add a comment | 2

for now, my best idea is -

1) stringify every value except array of dictionaries,

2) check if string content "null", then replace it with ""if true.

3) array of dictionaries, if stringified, will have 2 option - with [[ and ]](then checking every dictionary like above) or without - in case of "images": <null>,(so <null> should be replaced with[[]]. but I have about 7 requests with different data, should be parsed this strange way, and I hope to found more pretty decision.

How to remove a prefix from a string, Swift's string have a built-in hasPrefix() method that returns true if the string starts with specific letters, but they don't have a way to remove those  To receive the latest developer news, visit and subscribe to our News and Updates.

Here's a protocolish solution, that goes recursively through dictionaries and arrays:

/// Allows clients to ask the receiver to remove any `NSNull` instances
protocol NullStripable {
    func strippingNulls() -> Self
}

extension Array: NullStripable {
    func strippingNulls() -> Self {
        return compactMap {
            switch $0 {
            case let strippable as NullStripable:
                // the forced cast here is necessary as the compiler sees
                // `strippable` as NullStripable, as we casted it from `Element`
                return (strippable.strippingNulls() as! Element)
            case is NSNull:
                return nil
            default:
                return $0
            }
        }
    }
}

extension Dictionary: NullStripable {
    func strippingNulls() -> Self {
        return compactMapValues {
            switch $0 {
            case let strippable as NullStripable:
                // the forced cast here is necessary as the compiler sees
                // `strippable` as NullStripable, as we casted it from `Value`
                return (strippable.strippingNulls() as! Value)
            case is NSNull:
                return nil
            default:
                return $0
            }
        }
    }
}

Usage example:

let dict: [String: Any] = [
    "items": ["info_editable": true,
              "name": "Android Q",
              "is_message": true,
              "images": [["id": 92,
                          "image": "/media/product/102.png"]],
              "video_description": NSNull(),
              "is_valid": true],
    "somethingElse": NSNull()
]

print(dict.strippingNulls())

Sample output:

["items": ["name": "Android Q", "info_editable": true, "images": [["image": "/media/product/102.png", "id": 92]], "is_message": true, "is_valid": true]]

Hands-On Full-Stack Development with Swift: Develop full-stack web , Develop full-stack web and native mobile applications using Swift and Vapor This method is invoked when you make a DELETE HTTP request to the /items the object even if the attributes are not passed and will replace attributes that are​  Swift Replace String Example Call replaceSubrange to replace strings. Use replacingOccurrences and replacingCharacters.

How to remove last character from a string in Swift, To remove the last character from a string we need to use the removeLast() method in swift. Here is an example that removes the last character  The Swift equivalent to NSMutableArray's removeObject is: var array = ["alpha", "beta", "gamma"] if let index = array.firstIndex(of: "beta") { array.remove(at: index) } if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

Remove Exchange Account From Phone, iOS. Use the instructions below to remove an Exchange account on your iPhone, iPod Touch, or iPad. These steps apply to devices running iOS 5.5 or  Stack Overflow Public To make it work with Swift 3.0 and also remove white spaces This is an easy way to remove or replace any repeating pattern of characters

Swift OS X Programming for Absolute Beginners, removeAll() To see how to delete items from an array, follow these steps: 1. Make sure the you can also replace an existing item with a new value. All you have  It's an extremely fast and efficient way to search and replace complex text tens of thousands of times, and it's all available for Swift developers to use. In this tutorial you'll learn how to create regular expressions using NSRegularExpression , and how to match a variety of regular expressions using the most important syntax.

Comments
  • var updatedDictionary = Dictionary(uniqueKeysWithValues: yourDictionary.map { ($0, $1 != nil ? $1! : "") })