标签: swift4

Swift:自定义编码器/解码器到字符串资源格式

我一直在玩,Codable并从文件中读取和写入JSON.现在我想写一个Coder可以读写iOS .strings文件的自定义.谁能帮我这个?我发现协议EncoderDecoder,但我不知道我应该实现此:

class StringsEncoder {}

extension StringsEncoder: Encoder {
    var codingPath: [CodingKey?] {
        return []
    }

    var userInfo: [CodingUserInfoKey : Any] {
        return [:]
    }

    func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {

    }

    func unkeyedContainer() -> UnkeyedEncodingContainer {

    }

    func singleValueContainer() -> SingleValueEncodingContainer {

    }
}

extension StringsEncoder: Decoder {
    func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {

    }

    func unkeyedContainer() throws -> …
Run Code Online (Sandbox Code Playgroud)

swift swift4 codable decodable encodable

35
推荐指数
1
解决办法
3928
查看次数

在Swift 4中不推荐使用init(colorLiteralRed:,green:,blue:,alpha :)

let startingColorOfGradient = UIColor(colorLiteralRed: 255/255, green: 
255/255, blue: 255/255, alpha: 1.0).cgColor
let endingColorOFGradient = UIColor(colorLiteralRed: 251/255, green: 
247/255, blue: 234/255, alpha: 1.0).cgColor
let gradient: CAGradientLayer = CAGradientLayer()
Run Code Online (Sandbox Code Playgroud)

错误:

'init(colorLiteralRed:green:blue:alpha :)'在Swift 4.0中被淘汰(Swift._ExpressibleByColorLiteral)

如果init(colorLiteralRed:,green:,blue:,alpha:)在Swift 4中弃用,如何使用渐变颜色?

uicolor swift4

33
推荐指数
1
解决办法
1万
查看次数

使用JSONEncoder对符合协议的类型进行编码/解码

我正在尝试使用Swift 4中的新JSONDecoder/Encoder找到符合swift协议的编码/解码结构数组的最佳方法.

我举了一个例子来说明问题:

首先,我们有一个协议Tag和一些符合这个协议的类型.

protocol Tag: Codable {
    var type: String { get }
    var value: String { get }
}

struct AuthorTag: Tag {
    let type = "author"
    let value: String
}

struct GenreTag: Tag {
    let type = "genre"
    let value: String
}
Run Code Online (Sandbox Code Playgroud)

然后我们有一个Type文章,它有一个标签数组.

struct Article: Codable {
    let tags: [Tag]
    let title: String
}
Run Code Online (Sandbox Code Playgroud)

最后,我们对文章进行编码或解码

let article = Article(tags: [AuthorTag(value: "Author Tag Value"), GenreTag(value:"Genre Tag Value")], title: "Article Title")


let jsonEncoder = JSONEncoder()
let jsonData = try …
Run Code Online (Sandbox Code Playgroud)

encoding json swift swift4 codable

32
推荐指数
3
解决办法
2万
查看次数

Swift 4 Codable; 如何使用单根级别密钥解码对象

我正在使用Codable带有JSON数据的Swift 4 协议.我的数据被格式化为在根级别有一个键,其中一个对象值包含我需要的属性,例如:

{
  "user": {
    "id": 1,
    "username": "jdoe"
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个User可以解码user密钥的结构:

struct User: Codable {
  let id: Int
  let username: String
}
Run Code Online (Sandbox Code Playgroud)

由于idusername是的性质user,而不是在根级别,我需要使一个包装类型,如下所示:

struct UserWrapper: Codable {
  let user: User
}
Run Code Online (Sandbox Code Playgroud)

然后,我可以通过UserWrapper,解码JSON ,并User解码.它似乎是很多冗余代码,因为我需要在我拥有的每种类型上都有一个额外的包装器.有没有办法避免这种包装模式或更正确/优雅的方式来处理这种情况?

json deserialization swift swift4 codable

32
推荐指数
4
解决办法
1万
查看次数

具有Void关联类型的Generic Swift 4枚举

TL;博士

是否可以实例化具有相关类型值的通用Swift 4枚举成员Void

背景

我正在使用一个简单的结果枚举(类似于antitypical结果):

enum Result<T> {
  case success(T)
  case error(Error?)
}
Run Code Online (Sandbox Code Playgroud)

现在我想用这个枚举来表示一个不产生实际结果值的操作的结果; 操作成功失败.为此,我将类型定义为Result<Void>,但我正在努力如何创建Result实例,既不起作用let res: Result<Void> = .successlet res: Result<Void> = .success()不起作用.

enums swift swift4

31
推荐指数
3
解决办法
1万
查看次数

关闭元组不支持Xcode 9 Swift 4中的解构

在Xcode 9中为Swift 4进行光泽项目之后

我得到以下错误,我不知道

闭包元组参数'(key:_,value:_)'不支持解构

码:

extension Dictionary
{
    init(elements: [Element]) {
        self.init()
        for (key, value) in elements {
            self[key] = value
        }
    }

    func flatMap<KeyPrime, ValuePrime>(_ transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime:ValuePrime] {
        return Dictionary<KeyPrime, ValuePrime>(elements: try flatMap({ (key, value) in
            return try transform(key, value)
        }))
    }
}
Run Code Online (Sandbox Code Playgroud)

此时出现错误 try flatMap({ (key, value)in

ios swift swift4 xcode9-beta

30
推荐指数
3
解决办法
1万
查看次数

如何使用Swift4中的Codable转换带有可选小数秒的日期字符串

我正在用Swift的Codable替换旧的JSON解析代码,并且遇到了一些麻烦.我想这不是一个可编码的问题,因为它是一个DateFormatter问题.

从结构开始

 struct JustADate: Codable {
    var date: Date
 }
Run Code Online (Sandbox Code Playgroud)

和一个json字符串

let json = """
  { "date": "2017-06-19T18:43:19Z" }
"""
Run Code Online (Sandbox Code Playgroud)

现在让我们解码

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

let data = json.data(using: .utf8)!
let justADate = try! decoder.decode(JustADate.self, from: data) //all good
Run Code Online (Sandbox Code Playgroud)

但是,如果我们更改日期以使其具有小数秒,例如:

let json = """
  { "date": "2017-06-19T18:43:19.532Z" }
"""
Run Code Online (Sandbox Code Playgroud)

现在它打破了.日期有时会以小秒数回归,有时则不会.我以前解决它的方式是在我的映射代码中我有一个转换函数,它尝试使用和不使用小数秒的dateFormats.我不太确定如何使用Codable来处理它.有什么建议?

nsdateformatter swift dateformatter swift4 codable

30
推荐指数
2
解决办法
6430
查看次数

Swift 4转换错误 - NSAttributedStringKey:Any

我最近转换了我的应用程序并且一直收到错误

"无法将'[String:Any]'类型的值转换为预期的参数类型'[NSAttributedStringKey:Any]?"

barButtonItem.setTitleTextAttributes(attributes, for: .normal)

整码:

 class func getBarButtonItem(title:String) -> UIBarButtonItem {
    let barButtonItem = UIBarButtonItem.init(title: title, style: .plain, target: nil, action: nil)
    let attributes = [NSAttributedStringKey.font.rawValue:  UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
    barButtonItem.setTitleTextAttributes(attributes, for: .normal)

    return barButtonItem
}
Run Code Online (Sandbox Code Playgroud)

swift4

29
推荐指数
3
解决办法
3万
查看次数

Swift 4,必须仅从主线程警告中使用

我用Swift4的时候Xcode 9给了我

UIApplication.delegate只能从主线程使用

....必须仅从主线程使用

从后台线程组调用的UI API

紫色警告.

我的代码;

var appDelegate = UIApplication.shared.delegate as! AppDelegate
public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let prefs:UserDefaults = UserDefaults.standard
var deviceUUID = UIDevice.current.identifierForVendor!.uuidString
Run Code Online (Sandbox Code Playgroud)

警告线是;

  public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)

像这样的另一个警告;

 let parameters = [
                        "tel": "\(self.phone.text!)"
                        ] as [String : String]
Run Code Online (Sandbox Code Playgroud)

UITextField.text只能从主线程使用

同样的错误..

我该如何解决?任何的想法 ?

appdelegate swift4 xcode9

28
推荐指数
1
解决办法
3万
查看次数

无法加载优化模型 - GoogleMaps SDK IOS

从CocoaPods安装Google Maps SDK后,我收到此错误.

CoreData: annotation:  Failed to load optimized model at path '/Users/nabeel/Library/Developer/CoreSimulator/Devices/96078737-8063-4BC1-97DB-7FECEC6835D9/data/Containers/Bundle/Application/972CD686-82DD-4357-9CDD-65A735D82190/My-APP-Beta.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileVersionID.omo'
CoreData: annotation:  Failed to load optimized model at path '/Users/nabeel/Library/Developer/CoreSimulator/Devices/96078737-8063-4BC1-97DB-7FECEC6835D9/data/Containers/Bundle/Application/972CD686-82DD-4357-9CDD-65A735D82190/My-APP-Beta.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileVersionID.omo'
CoreData: annotation:  Failed to load optimized model at path '/Users/nabeel/Library/Developer/CoreSimulator/Devices/96078737-8063-4BC1-97DB-7FECEC6835D9/data/Containers/Bundle/Application/972CD686-82DD-4357-9CDD-65A735D82190/My-APP-Beta.app/GoogleMaps.bundle/GMSCacheStorage.momd/StorageWithTileVersionID.omo'
Run Code Online (Sandbox Code Playgroud)

我已经尝试了pod更新和pod安装,但同样的问题.

sdk google-maps ios swift4 xcode9.1

28
推荐指数
3
解决办法
1万
查看次数