标签: swift4

如何在Core Data中使用swift 4 Codable?

Codable似乎是一个非常令人兴奋的功能.但我想知道我们如何在核心数据中使用它?特别是,是否可以直接从/向NSManagedObject编码/解码JSON?

我尝试了一个非常简单的例子:

在此输入图像描述

并定义Foo自己:

import CoreData

@objc(Foo)
public class Foo: NSManagedObject, Codable {}
Run Code Online (Sandbox Code Playgroud)

但是当它像这样使用时:

let json = """
{
    "name": "foo",
    "bars": [{
        "name": "bar1",
    }], [{
        "name": "bar2"
    }]
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let foo = try! decoder.decode(Foo.self, from: json)
print(foo)
Run Code Online (Sandbox Code Playgroud)

编译器因此错误而失败:

super.init isn't called on all paths before returning from initializer
Run Code Online (Sandbox Code Playgroud)

目标文件是定义的文件 Foo

我想我可能做错了,因为我甚至没有通过NSManagedObjectContext,但我不知道在哪里坚持下去.

核心数据是否支持Codable

core-data swift swift4 xcode9 codable

43
推荐指数
4
解决办法
2万
查看次数

如何在Xcode 9上构建Swift 3项目?

Xcode 9发行说明表示支持Swift 3编译:

Swift 4和Swift 3,Swift 4和Swift 3目标的一个编译器可以在同一个项目中一起编译.

我已经安装了Xcode 9 beta.但是,当我按下Build时,它会显示一堆错误.在Xcode 9中使用Swift 3时是否需要做一些特殊的准备工作?

UPD: 使用Swift 3.1编译的模块无法在Swift 4.0中导入

使用Swift 3.1编译的模块无法在Swift 4.0中导入

xcode ios swift3 swift4 xcode9

42
推荐指数
2
解决办法
4万
查看次数

条形码快速4

我正在尝试将mi app升级到swift 4,但条形码阅读器无法正常工作.

我已经隔离了条形码阅读器代码,但仍然无法正常工作.相机可以正常工作但不会检测到条形码.

代码在swift 3 iOS 10上运行得很好.

这是完整的代码

import AVFoundation
import UIKit

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.black
    captureSession = AVCaptureSession()

    let videoCaptureDevice = AVCaptureDevice.default(for: AVMediaType.video)
    let videoInput: AVCaptureDeviceInput

    do {
        videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice!)
    } catch {
        return
    }

    if (captureSession.canAddInput(videoInput)) {
        captureSession.addInput(videoInput)
    } else {
        failed();
        return;
    }

    let metadataOutput = AVCaptureMetadataOutput()

    if (captureSession.canAddOutput(metadataOutput)) {
        captureSession.addOutput(metadataOutput)

        metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        metadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.ean8, AVMetadataObject.ObjectType.ean13, …
Run Code Online (Sandbox Code Playgroud)

barcode avcapturesession swift4 ios11 xcode9-beta

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

Codable类不符合协议Decodable

为什么我得到"类型'书签'不符合协议'可解码'"错误消息?

class Bookmark: Codable {
   weak var publication: Publication?
   var indexPath: [Int]
   var locationInText = 0

   enum CodingKeys: String, CodingKey {
      case indexPath
      case locationInText
   }

   init(publication: Publication?, indexPath: [Int]) {
      self.publication = publication
      self.indexPath = indexPath
   }
}
Run Code Online (Sandbox Code Playgroud)

我不希望保存出版物var,因为出版物拥有书签,但书签需要知道它属于哪个出版物.Publication的解码初始化将书签引用设置为自身.

swift swift4 codable decodable

40
推荐指数
8
解决办法
5万
查看次数

使用JSONEncoder将nil值编码为null

我正在使用Swift 4 JSONEncoder.我有一个Codable带有可选属性的结构,我希望这个属性在null值为时在生成的JSON数据中显示为值nil.但是,JSONEncoder丢弃该属性并且不将其添加到JSON输出.有没有办法配置,JSONEncoder以便它保留密钥并null在这种情况下将其设置为?

下面的代码片段会产生{"number":1},但我更愿意给它{"string":null,"number":1}:

struct Foo: Codable {
  var string: String? = nil
  var number: Int = 1
}

let encoder = JSONEncoder()
let data = try! encoder.encode(Foo())
print(String(data: data, encoding: .utf8)!)
Run Code Online (Sandbox Code Playgroud)

json ios swift4 codable

39
推荐指数
2
解决办法
5840
查看次数

UIImageJPEGRepresentation已被实例方法UIImage.jpegData(compressionQuality :)取代

我试图将照片上传到Firebase,但它给了我这个错误.它在Xcode 10之前工作.我收到此错误:

'UIImageJPEGRepresentation'已被实例方法'UIImage.jpegData(compressionQuality :)'取代

我不知道如何使用这个功能.

import UIKit
import Firebase

class SignUpViewController:UIViewController {
    @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var tapToChangeProfileButton: UIButton!

    var continueButton:RoundedWhiteButton!
    var imagePicker:UIImagePickerController!

    override func viewDidLoad() {
        super.viewDidLoad()

          continueButton.addTarget(self, action: #selector(handleSignUp), for: 
          .touchUpInside)
        let imageTap = UITapGestureRecognizer(target: self, action: 
        #selector(openImagePicker))
        profileImageView.isUserInteractionEnabled = true
        profileImageView.addGestureRecognizer(imageTap)
        profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
        profileImageView.clipsToBounds = true

        imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = true
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
    }

    func uploadProfileImage(_ image:UIImage, completion: @escaping ((_ url:URL?)->())) {
        guard let uid = …
Run Code Online (Sandbox Code Playgroud)

ios swift swift4 ios12

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

'subscript'不可用:不能使用CountableClosedRange <Int>下标String,请参阅文档注释以供讨论

在斯威夫特4,当我尝试采取我得到这个错误SubstringString使用标语法.

'subscript'不可用:不能使用CountableClosedRange下标String,请参阅文档注释以供讨论

例如:

let myString: String = "foobar"
let mySubstring: Substring = myString[1..<3]
Run Code Online (Sandbox Code Playgroud)

两个问题:

  1. 我该如何解决这个错误?
  2. 错误中提到的"讨论文档评论"在哪里?

string swift swift4

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

Swift中的单行if语句

如何从Objective-C将以下内容转换为Swift?

if (myVar) return;
Run Code Online (Sandbox Code Playgroud)

Swift不在条件周围使用括号,但是下面的代码给出了错误.

if myVar return 
Run Code Online (Sandbox Code Playgroud)

objective-c ios swift swift3 swift4

36
推荐指数
5
解决办法
5万
查看次数

无法将NSAttributedString.DocumentAttributeKey类型的值转换为.DocumentReadingOptionKey

我在SO上找到了这个字符串扩展,允许我将html代码转换为属性字符串:

func html2AttributedString() -> NSAttributedString {
    return try! NSAttributedString(data: self.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
}
Run Code Online (Sandbox Code Playgroud)

它在Swift 3中运行良好,但是对于Swift 4,Xcode抱怨:

无法将'NSAttributedString.DocumentAttributeKey'类型的值转换为预期的字典键类型'NSAttributedString.DocumentReadingOptionKey'

我该如何解决?

ios swift swift4 nsattributedstringkey

36
推荐指数
4
解决办法
2万
查看次数

用于observeValue的Swift 4方法(forKeyPath:...)

我一直试图找到一个例子,但我所看到的并不适用于我的情况.

什么是以下代码的等价物:

object.addObserver(self, forKeyPath: "keyPath", options: [.new], context: nil)

override public func observeValue(
    forKeyPath keyPath: String?,
    of object: Any?, 
    change: [NSKeyValueChangeKey : Any]?, 
    context: UnsafeMutableRawPointer?) {

}
Run Code Online (Sandbox Code Playgroud)

上面的代码有效,但我从SwiftLink收到警告:

使用Swift 3.2或更高版本时,首选基于新块的KVO API和键路径.

如果你能指出我正确的方向,我感激不尽.

key-value-observing swift swift4 keypaths

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