repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Guichaguri/react-native-track-player
|
ios/RNTrackPlayer/Models/Track.swift
|
1
|
4320
|
//
// Track.swift
// RNTrackPlayer
//
// Created by David Chavez on 12.08.17.
// Copyright © 2017 David Chavez. All rights reserved.
//
import Foundation
import MediaPlayer
import AVFoundation
class Track: NSObject, AudioItem, TimePitching, AssetOptionsProviding {
let url: MediaURL
@objc var title: String
@objc var artist: String
var date: String?
var desc: String?
var genre: String?
var duration: Double?
var skipped: Bool = false
var artworkURL: MediaURL?
let headers: [String: Any]?
let pitchAlgorithm: String?
@objc var album: String?
@objc var artwork: MPMediaItemArtwork?
private var originalObject: [String: Any]
init?(dictionary: [String: Any]) {
guard let title = dictionary["title"] as? String,
let artist = dictionary["artist"] as? String,
let url = MediaURL(object: dictionary["url"])
else { return nil }
self.url = url
self.title = title
self.artist = artist
self.date = dictionary["date"] as? String
self.album = dictionary["album"] as? String
self.genre = dictionary["genre"] as? String
self.desc = dictionary["description"] as? String
self.duration = dictionary["duration"] as? Double
self.headers = dictionary["headers"] as? [String: Any]
self.artworkURL = MediaURL(object: dictionary["artwork"])
self.pitchAlgorithm = dictionary["pitchAlgorithm"] as? String
self.originalObject = dictionary
}
// MARK: - Public Interface
func toObject() -> [String: Any] {
return originalObject
}
func updateMetadata(dictionary: [String: Any]) {
self.title = (dictionary["title"] as? String) ?? self.title
self.artist = (dictionary["artist"] as? String) ?? self.artist
self.date = dictionary["date"] as? String
self.album = dictionary["album"] as? String
self.genre = dictionary["genre"] as? String
self.desc = dictionary["description"] as? String
self.duration = dictionary["duration"] as? Double
self.artworkURL = MediaURL(object: dictionary["artwork"])
self.originalObject = self.originalObject.merging(dictionary) { (_, new) in new }
}
// MARK: - AudioItem Protocol
func getSourceUrl() -> String {
return url.isLocal ? url.value.path : url.value.absoluteString
}
func getArtist() -> String? {
return artist
}
func getTitle() -> String? {
return title
}
func getAlbumTitle() -> String? {
return album
}
func getSourceType() -> SourceType {
return url.isLocal ? .file : .stream
}
func getArtwork(_ handler: @escaping (UIImage?) -> Void) {
if let artworkURL = artworkURL?.value {
if(self.artworkURL?.isLocal ?? false){
let image = UIImage.init(contentsOfFile: artworkURL.path);
handler(image);
} else {
URLSession.shared.dataTask(with: artworkURL, completionHandler: { (data, _, error) in
if let data = data, let artwork = UIImage(data: data), error == nil {
handler(artwork)
}
handler(nil)
}).resume()
}
}
handler(nil)
}
// MARK: - TimePitching Protocol
func getPitchAlgorithmType() -> AVAudioTimePitchAlgorithm {
if let pitchAlgorithm = pitchAlgorithm {
switch pitchAlgorithm {
case PitchAlgorithm.linear.rawValue:
return .varispeed
case PitchAlgorithm.music.rawValue:
return .spectral
case PitchAlgorithm.voice.rawValue:
return .timeDomain
default:
return .lowQualityZeroLatency
}
}
return .lowQualityZeroLatency
}
// MARK: - Authorizing Protocol
func getAssetOptions() -> [String: Any] {
if let headers = headers {
return ["AVURLAssetHTTPHeaderFieldsKey": headers]
}
return [:]
}
}
|
gpl-3.0
|
ed0512c4d20cc301b053f6692cc6f8b8
| 28.582192 | 101 | 0.564946 | 4.725383 | false | false | false | false |
vimeo/VIMVideoPlayer
|
Examples/VimeoPlayer-iOS-Example/VimeoPlayer-iOS-Example/ViewController.swift
|
1
|
4467
|
//
// ViewController.swift
// VIMVideoPlayer-iOS-Example
//
// Created by King, Gavin on 3/9/16.
// Copyright © 2016 Gavin King. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ViewController: UIViewController, VIMVideoPlayerViewDelegate
{
@IBOutlet weak var videoPlayerView: VIMVideoPlayerView!
@IBOutlet weak var slider: UISlider!
private var isScrubbing = false
override func viewDidLoad()
{
super.viewDidLoad()
self.setupVideoPlayerView()
self.setupSlider()
}
// MARK: Setup
private func setupVideoPlayerView()
{
self.videoPlayerView.player.looping = true
self.videoPlayerView.player.disableAirplay()
self.videoPlayerView.setVideoFillMode(AVLayerVideoGravityResizeAspectFill)
self.videoPlayerView.delegate = self
if let path = NSBundle.mainBundle().pathForResource("waterfall", ofType: "mp4")
{
self.videoPlayerView.player.setURL(NSURL(fileURLWithPath: path))
}
else
{
assertionFailure("Video file not found!")
}
}
private func setupSlider()
{
self.slider.addTarget(self, action: "scrubbingDidStart", forControlEvents: UIControlEvents.TouchDown)
self.slider.addTarget(self, action: "scrubbingDidChange", forControlEvents: UIControlEvents.ValueChanged)
self.slider.addTarget(self, action: "scrubbingDidEnd", forControlEvents: UIControlEvents.TouchUpInside)
self.slider.addTarget(self, action: "scrubbingDidEnd", forControlEvents: UIControlEvents.TouchUpOutside)
}
// MARK: Actions
@IBAction func didTapPlayPauseButton(sender: UIButton)
{
if self.videoPlayerView.player.playing
{
sender.selected = true
self.videoPlayerView.player.pause()
}
else
{
sender.selected = false
self.videoPlayerView.player.play()
}
}
// MARK: Scrubbing Actions
func scrubbingDidStart()
{
self.isScrubbing = true
self.videoPlayerView.player.startScrubbing()
}
func scrubbingDidChange()
{
guard let duration = self.videoPlayerView.player.player.currentItem?.duration
where self.isScrubbing == true else
{
return
}
let time = Float(CMTimeGetSeconds(duration)) * self.slider.value
self.videoPlayerView.player.scrub(time)
}
func scrubbingDidEnd()
{
self.videoPlayerView.player.stopScrubbing()
self.isScrubbing = false
}
// MARK: VIMVideoPlayerViewDelegate
func videoPlayerViewIsReadyToPlayVideo(videoPlayerView: VIMVideoPlayerView?)
{
self.videoPlayerView.player.play()
}
func videoPlayerView(videoPlayerView: VIMVideoPlayerView!, timeDidChange cmTime: CMTime)
{
guard let duration = self.videoPlayerView.player.player.currentItem?.duration
where self.isScrubbing == false else
{
return
}
let durationInSeconds = Float(CMTimeGetSeconds(duration))
let timeInSeconds = Float(CMTimeGetSeconds(cmTime))
self.slider.value = timeInSeconds / durationInSeconds
}
}
|
mit
|
509663bf583ff90f192833b204d365bf
| 31.136691 | 113 | 0.659875 | 4.945736 | false | false | false | false |
zvonler/PasswordElephant
|
external/github.com/CryptoSwift/Tests/Tests/PaddingTests.swift
|
3
|
3608
|
//
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
@testable import CryptoSwift
import XCTest
final class PaddingTests: XCTestCase {
func testPKCS7_0() {
let input: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
let expected: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16]
let padded = PKCS7.Padding().add(to: input, blockSize: 16)
XCTAssertEqual(padded, expected, "PKCS7 failed")
let clean = PKCS7.Padding().remove(from: padded, blockSize: nil)
XCTAssertEqual(clean, input, "PKCS7 failed")
}
func testPKCS7_1() {
let input: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5]
let expected: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 1]
let padded = PKCS7.Padding().add(to: input, blockSize: 16)
XCTAssertEqual(padded, expected, "PKCS7 failed")
let clean = PKCS7.Padding().remove(from: padded, blockSize: nil)
XCTAssertEqual(clean, input, "PKCS7 failed")
}
func testPKCS7_2() {
let input: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
let expected: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 2, 2]
let padded = PKCS7.Padding().add(to: input, blockSize: 16)
XCTAssertEqual(padded, expected, "PKCS7 failed")
let clean = PKCS7.Padding().remove(from: padded, blockSize: nil)
XCTAssertEqual(clean, input, "PKCS7 failed")
}
func testZeroPadding1() {
let input: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let expected: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0]
let padding = ZeroPadding()
XCTAssertEqual(padding.add(to: input, blockSize: 16), expected, "ZeroPadding failed")
XCTAssertEqual(padding.remove(from: padding.add(to: input, blockSize: 16), blockSize: 16), input, "ZeroPadding failed")
}
func testZeroPadding2() {
let input: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
let expected: Array<UInt8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let padding = ZeroPadding()
XCTAssertEqual(padding.add(to: input, blockSize: 16), expected, "ZeroPadding failed")
XCTAssertEqual(padding.remove(from: padding.add(to: input, blockSize: 16), blockSize: 16), input, "ZeroPadding failed")
}
static let allTests = [
("testPKCS7_0", testPKCS7_0),
("testPKCS7_1", testPKCS7_1),
("testPKCS7_2", testPKCS7_2),
("testZeroPadding1", testZeroPadding1),
("testZeroPadding2", testZeroPadding2),
]
}
|
gpl-3.0
|
01b0fc6046835233bcac6f5eb0a79fee
| 50.528571 | 217 | 0.620737 | 3.209075 | false | true | false | false |
MrThumb/mrthumb-swift
|
Example/Tests/ClientSpec.swift
|
1
|
1430
|
import Quick
import Nimble
import MrThumb
import Mockingjay
class ClientSpec: QuickSpec {
override func spec() {
let configuration = Configuration(accessId: "XX", secretId: "ZZ")
let client = Client(withConfiguration: configuration)
describe("createImage") {
let url = "http://sample.com/image"
let transformations = [
"resize": [
"height": 200
]
]
func apiRequest(_ configuration: MrThumb.Configuration) -> (_ request: URLRequest) -> Bool {
return { (request: URLRequest) in
let validMethod = http(.post, uri: "/api/v1/images")(request)
let validHeader = request.value(forHTTPHeaderField: "Authorization")!.range(of: "^APIAuth XX:(.+)$", options: .regularExpression) != nil
return validMethod && validHeader
}
}
beforeEach {
self.stub(apiRequest(configuration), http(200, headers: [:], download: nil))
}
it("returns success on completion") {
waitUntil { done in
client.createImage(url: url, transformations: transformations) { (success, data) in
expect(success).to(beTrue())
done()
}
}
}
}
}
}
|
mit
|
4534d26012033bf5ba0d7f800423f03d
| 32.255814 | 156 | 0.507692 | 5.257353 | false | true | false | false |
mrdepth/EVEOnlineAPI
|
EVEAPI/EVEAPI/EVEKillMails.swift
|
1
|
6099
|
//
// EVEKillMails.swift
// EVEAPI
//
// Created by Artem Shimanski on 29.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVEKillMailsVictim: EVEObject {
public var characterID: Int64 = 0
public var characterName: String = ""
public var corporationID: Int64 = 0
public var corporationName: String = ""
public var allianceID: Int64 = 0
public var allianceName: String = ""
public var factionID: Int64 = 0
public var factionName: String = ""
public var damageTaken: Int = 0
public var shipTypeID: Int = 0
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"characterID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"characterName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"corporationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"corporationName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"allianceID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"allianceName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"factionID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"factionName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"damageTaken":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"shipTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
]
}
}
public class EVEKillMailsAttacker: EVEObject {
public var characterID: Int64 = 0
public var characterName: String = ""
public var corporationID: Int64 = 0
public var corporationName: String = ""
public var allianceID: Int64 = 0
public var allianceName: String = ""
public var factionID: Int64 = 0
public var factionName: String = ""
public var securityStatus: Double = 0
public var damageDone: Double = 0
public var finalBlow: Bool = false
public var weaponTypeID: Int = 0
public var shipTypeID: Int = 0
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"characterID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"characterName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"corporationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"corporationName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"allianceID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"allianceName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"factionID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"factionName":EVESchemeElementType.String(elementName:nil, transformer:nil),
"securityStatus":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"damageDone":EVESchemeElementType.Double(elementName:nil, transformer:nil),
"finalBlow":EVESchemeElementType.Bool(elementName:nil, transformer:nil),
"weaponTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"shipTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
]
}
}
public class EVEKillMailsItem: EVEObject {
public var flag: EVEInventoryFlag = .none
public var qtyDropped: Int = 0
public var qtyDestroyed: Int = 0
public var typeID: Int = 0
public var items:[EVEKillMailsItem] = []
public var singleton: Bool = false
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"flag":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"qtyDropped":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"qtyDestroyed":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"typeID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"items":EVESchemeElementType.Rowset(elementName: nil, type: EVEKillMailsItem.self, transformer: nil),
"singleton":EVESchemeElementType.Bool(elementName:nil, transformer:nil),
]
}
}
public class EVEKillMailsKill: EVEObject {
public var killID: Int64 = 0
public var solarSystemID: Int = 0
public var killTime: Date = Date.distantPast
public var moonID: Int = 0
public var victim: [EVEKillMailsVictim] = []
public var attackers: [EVEKillMailsAttacker] = []
public var items: [EVEKillMailsItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"killID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"solarSystemID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"killTime":EVESchemeElementType.Date(elementName:nil, transformer:nil),
"moonID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"victim":EVESchemeElementType.Rowset(elementName: nil, type: EVEKillMailsVictim.self, transformer: nil),
"attackers":EVESchemeElementType.Rowset(elementName: nil, type: EVEKillMailsAttacker.self, transformer: nil),
"items":EVESchemeElementType.Rowset(elementName: nil, type: EVEKillMailsItem.self, transformer: nil)
]
}
}
public class EVEKillMails: EVEResult {
public var kills: [EVEKillMailsKill] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"kills":EVESchemeElementType.Rowset(elementName: nil, type: EVEKillMailsKill.self, transformer: nil)
]
}
}
|
mit
|
97f0130c05798b451cc32b87f61545bb
| 36.411043 | 112 | 0.761561 | 3.823197 | false | false | false | false |
aahmedae/blitz-news-ios
|
Blitz News/Controller/NewsListViewController.swift
|
1
|
2505
|
//
// NewsListViewController.swift
// Blitz News
//
// Created by Asad Ahmed on 5/16/17.
// VC responsible for displaying the news list for a news source
//
import UIKit
class NewsListViewController: NewsViewController
{
// MARK:- Outlets and Variables
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var refreshBarButton: UIBarButtonItem!
@IBOutlet weak var spinner: UIActivityIndicatorView!
var source: NewsSource!
fileprivate var newsItems = [NewsItem]()
override func viewDidLoad()
{
super.viewDidLoad()
loadNewsForSource()
// table view setup
tableView.indicatorStyle = .white
tableView.backgroundColor = UISettings.VC_BACKGROUND_COLOR
view.backgroundColor = UISettings.VC_BACKGROUND_COLOR
}
// Loads the news for the source
fileprivate func loadNewsForSource()
{
UIApplication.shared.isNetworkActivityIndicatorVisible = true
refreshBarButton.isEnabled = false
weak var weakSelf = self
NewsAPIManager.sharedInstance.newsItemsForSource(sourceID: source.sourceID!) { [unowned self] (data, error) in
if error == .none
{
if let news = data
{
weakSelf?.newsItems = news
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
weakSelf?.spinner.stopAnimating()
weakSelf?.refreshBarButton.isEnabled = true
weakSelf?.setupTableView(newsTableView: self.tableView, newsItems: self.newsItems)
}
}
}
else
{
// recevied error when downloading
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
weakSelf?.spinner.stopAnimating()
weakSelf?.refreshBarButton.isEnabled = true
let ac = NewsSourceVCHelper.alertDialogForError(error)
weakSelf?.present(ac, animated: true, completion: nil)
}
}
}
}
// User taps on the bar button to refresh the news list for this news source
@IBAction func refreshBarButtonTapped(_ sender: UIBarButtonItem)
{
loadNewsForSource()
}
}
|
mit
|
76d84d368e02daf5f2807fafbf7081a3
| 31.960526 | 118 | 0.586028 | 5.693182 | false | false | false | false |
samodom/UIKitSwagger
|
UIKitSwagger/Color/GrayscaleComponents.swift
|
1
|
2149
|
//
// GrayscaleComponents.swift
// UIKitSwagger
//
// Created by Sam Odom on 12/13/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import UIKit
/**
Convenience structure to hold the white and alpha component values of an instance of `UIColor`.
*/
public struct GrayscaleComponents: ColorComponents {
public let white: CGFloat
public let alpha: CGFloat
public init(white w: CGFloat, alpha a: CGFloat! = 1) {
white = w
alpha = a
}
/**
Required method for creating colors based on this component scheme.
*/
public func color() -> UIColor {
return UIColor(white: white, alpha: alpha)
}
}
/**
Equatability of grayscale components.
*/
extension GrayscaleComponents: Equatable {
}
public func ==(lhs: GrayscaleComponents, rhs: GrayscaleComponents) -> Bool {
return componentValuesEqualWithinTolerance(lhs.white, rhs.white) &&
componentValuesEqualWithinTolerance(lhs.alpha, rhs.alpha)
}
public extension UIColor {
/**
Property that returns the grayscale components of the color in a structure.
*/
public var grayscaleComponents: GrayscaleComponents {
var whiteValue = CGFloat(0)
var alphaValue = CGFloat(0)
getWhite(&whiteValue, alpha: &alphaValue)
return GrayscaleComponents(white: whiteValue, alpha: alphaValue)
}
}
public extension UIColor {
/**
Property to provide the white component value of the color.
*/
public var white: CGFloat {
return grayscaleComponents.white
}
}
/**
Component conversion methods.
*/
public extension GrayscaleComponents {
/**
Converts grayscale components into RGB components.
*/
public func asRGBComponents() -> RGBComponents {
return color().rgbComponents
}
/**
Converts grayscale components into HSB components.
*/
public func asHSBComponents() -> HSBComponents {
return color().hsbComponents
}
/**
Converts grayscale components into CMYK components.
*/
public func asCMYKComponents() -> CMYKComponents {
return color().cmykComponents
}
}
|
mit
|
ecb455ce825813444b4b6236056573a9
| 21.385417 | 95 | 0.67101 | 4.48643 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/UserInterface/Location/LocationSelectionViewController.swift
|
1
|
9151
|
//
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireDataModel
import MapKit
import CoreLocation
import UIKit
protocol LocationSelectionViewControllerDelegate: AnyObject {
func locationSelectionViewController(_ viewController: LocationSelectionViewController, didSelectLocationWithData locationData: LocationData)
func locationSelectionViewControllerDidCancel(_ viewController: LocationSelectionViewController)
}
final class LocationSelectionViewController: UIViewController {
weak var delegate: LocationSelectionViewControllerDelegate?
let locationButton: IconButton = {
let button = IconButton()
button.setIcon(.location, size: .tiny, for: [])
button.borderWidth = 0.5
button.setBorderColor(SemanticColors.View.borderInputBar, for: .normal)
button.circular = true
button.backgroundColor = SemanticColors.View.backgroundDefault
button.setIconColor(SemanticColors.Icon.foregroundDefault, for: .normal)
return button
}()
let locationButtonContainer = UIView()
fileprivate var mapView = MKMapView()
fileprivate let toolBar = ModalTopBar()
fileprivate let locationManager = CLLocationManager()
fileprivate let geocoder = CLGeocoder()
fileprivate let sendViewController = LocationSendViewController()
fileprivate let pointAnnotation = MKPointAnnotation()
private lazy var annotationView: MKPinAnnotationView = MKPinAnnotationView(annotation: pointAnnotation, reuseIdentifier: String(describing: type(of: self)))
fileprivate var userShowedInitially = false
fileprivate var mapDidRender = false
fileprivate var userLocationAuthorized: Bool {
let status = CLLocationManager.authorizationStatus()
return status == .authorizedAlways || status == .authorizedWhenInUse
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
mapView.delegate = self
toolBar.delegate = self
sendViewController.delegate = self
configureViews()
createConstraints()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !userLocationAuthorized { mapView.restoreLocation(animated: true) }
locationManager.requestWhenInUseAuthorization()
updateUserLocation()
endEditing()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
locationManager.stopUpdatingHeading()
mapView.storeLocation()
}
fileprivate func configureViews() {
addChild(sendViewController)
sendViewController.didMove(toParent: self)
[mapView, sendViewController.view, toolBar, locationButton].forEach(view.addSubview)
locationButton.addTarget(self, action: #selector(locationButtonTapped), for: .touchUpInside)
mapView.isRotateEnabled = false
mapView.isPitchEnabled = false
toolBar.configure(title: title!, subtitle: nil, topAnchor: safeTopAnchor)
pointAnnotation.coordinate = mapView.centerCoordinate
mapView.addSubview(annotationView)
}
fileprivate func createConstraints() {
guard let sendController = sendViewController.view else { return }
[mapView, sendController, annotationView, toolBar, locationButton].prepareForLayout()
NSLayoutConstraint.activate([
mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
mapView.topAnchor.constraint(equalTo: view.topAnchor, constant: UIScreen.safeArea.top),
mapView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -UIScreen.safeArea.bottom),
sendController.leadingAnchor.constraint(equalTo: view.leadingAnchor),
sendController.trailingAnchor.constraint(equalTo: view.trailingAnchor),
sendController.bottomAnchor.constraint(equalTo: view.bottomAnchor),
sendController.heightAnchor.constraint(equalToConstant: 56 + UIScreen.safeArea.bottom),
toolBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
toolBar.topAnchor.constraint(equalTo: view.topAnchor),
toolBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
annotationView.centerXAnchor.constraint(equalTo: mapView.centerXAnchor, constant: 8.5),
annotationView.bottomAnchor.constraint(equalTo: mapView.centerYAnchor, constant: 5),
annotationView.heightAnchor.constraint(equalToConstant: 39),
annotationView.widthAnchor.constraint(equalToConstant: 32),
locationButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
locationButton.bottomAnchor.constraint(equalTo: sendController.topAnchor, constant: -16),
locationButton.widthAnchor.constraint(equalToConstant: 28),
locationButton.heightAnchor.constraint(equalToConstant: 28)
])
}
@objc fileprivate func locationButtonTapped(_ sender: IconButton) {
zoomToUserLocation(true)
}
fileprivate func updateUserLocation() {
mapView.showsUserLocation = userLocationAuthorized
if userLocationAuthorized {
locationManager.startUpdatingLocation()
}
}
fileprivate func zoomToUserLocation(_ animated: Bool) {
guard userLocationAuthorized else { return presentUnauthorizedAlert() }
let region = MKCoordinateRegion(center: mapView.userLocation.coordinate, latitudinalMeters: 50, longitudinalMeters: 50)
mapView.setRegion(region, animated: animated)
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return wr_supportedInterfaceOrientations
}
fileprivate func presentUnauthorizedAlert() {
let localize: (String) -> String = { ("location.unauthorized_alert." + $0).localized }
let alertController = UIAlertController(title: localize("title"), message: localize("message"), preferredStyle: .alert)
let cancelAction = UIAlertAction(title: localize("cancel"), style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: localize("settings"), style: .default) { _ in
guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(url)
}
[cancelAction, settingsAction].forEach(alertController.addAction)
present(alertController, animated: true, completion: nil)
}
fileprivate func formatAndUpdateAddress() {
guard mapDidRender else { return }
geocoder.reverseGeocodeLocation(mapView.centerCoordinate.location) { [weak self] placemarks, error in
guard nil == error, let placemark = placemarks?.first else { return }
if let address = placemark.formattedAddress(false), !address.isEmpty {
self?.sendViewController.address = address
} else {
self?.sendViewController.address = nil
}
}
}
}
extension LocationSelectionViewController: LocationSendViewControllerDelegate {
func locationSendViewControllerSendButtonTapped(_ viewController: LocationSendViewController) {
let locationData = mapView.locationData(name: viewController.address)
delegate?.locationSelectionViewController(self, didSelectLocationWithData: locationData)
dismiss(animated: true, completion: nil)
}
}
extension LocationSelectionViewController: ModalTopBarDelegate {
func modelTopBarWantsToBeDismissed(_ topBar: ModalTopBar) {
delegate?.locationSelectionViewControllerDidCancel(self)
}
}
extension LocationSelectionViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
updateUserLocation()
}
}
extension LocationSelectionViewController: MKMapViewDelegate {
func mapViewDidFinishRenderingMap(_ mapView: MKMapView, fullyRendered: Bool) {
mapDidRender = true
formatAndUpdateAddress()
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
formatAndUpdateAddress()
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
if !userShowedInitially {
userShowedInitially = true
zoomToUserLocation(true)
}
}
}
|
gpl-3.0
|
5b9db907c678624afb774bb8d5d539cd
| 40.785388 | 160 | 0.722763 | 5.593521 | false | false | false | false |
terryokay/learnAnimationBySwift
|
learnAnimation/learnAnimation/StudentInfoCell.swift
|
1
|
2010
|
//
// StudentInfoCell.swift
// learnAnimation
//
// Created by likai on 2017/4/18.
// Copyright © 2017年 terry. All rights reserved.
//
import UIKit
class StudentInfoCell: CustomCell {
fileprivate var nameLabel : UILabel!
fileprivate var ageLabel : UILabel!
override func setupCell() {
self.selectionStyle = .none
}
override func buildSubView() {
nameLabel = UILabel(frame: CGRect(x: 20, y: 0, width: 200, height: 60))
nameLabel.font = UIFont.AppleSDGothicNeoThin(20)
self.addSubview(nameLabel)
ageLabel = UILabel(frame: CGRect(x: Width() - 220, y: 0, width: 200, height: 60))
ageLabel.textAlignment = .right
ageLabel.font = UIFont.AppleSDGothicNeoThin(20)
self.addSubview(ageLabel)
self.addSubview(UIView.CreateLine(CGRect(x: 0, y: 59.5, width: Width(), height: 0.5), lineColor: UIColor.gray.alpha(0.1)))
}
override func loadContent() {
let model = data as! StudentModel
nameLabel.text = model.name
ageLabel.text = model.age.stringValue
}
override func selectedEvent() {
showSelectedAnimation()
}
fileprivate func showSelectedAnimation(){
let tempView = UIView(frame: CGRect(x: 0, y: 0, width: Width(), height: 60))
tempView.backgroundColor = UIColor.cyan.alpha(0.2)
tempView.alpha = 0
self.addSubview(tempView)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
tempView.alpha = 0.8
}) { (finished) in
UIView.animate(withDuration: 0.2, delay: 0.1, options: .curveEaseOut, animations: {
tempView.alpha = 0
}, completion: { (finished) in
tempView.removeFromSuperview()
})
}
}
}
|
mit
|
e6f0076b4f92bb8aee665417fc879a44
| 26.121622 | 130 | 0.558545 | 4.489933 | false | false | false | false |
i-schuetz/SwiftCharts
|
SwiftCharts/Utils/Operators.swift
|
1
|
1213
|
//
// Operators.swift
// SwiftCharts
//
// Created by ischuetz on 16/07/16.
// Copyright © 2016 ivanschuetz. All rights reserved.
//
import Foundation
infix operator =~ : ComparisonPrecedence
func =~ (a: Float, b: Float) -> Bool {
return fabsf(a - b) < Float.ulpOfOne
}
func =~ (a: CGFloat, b: CGFloat) -> Bool {
return abs(a - b) < CGFloat.ulpOfOne
}
func =~ (a: Double, b: Double) -> Bool {
return fabs(a - b) < Double.ulpOfOne
}
infix operator !=~ : ComparisonPrecedence
func !=~ (a: Float, b: Float) -> Bool {
return !(a =~ b)
}
func !=~ (a: CGFloat, b: CGFloat) -> Bool {
return !(a =~ b)
}
func !=~ (a: Double, b: Double) -> Bool {
return !(a =~ b)
}
infix operator <=~ : ComparisonPrecedence
func <=~ (a: Float, b: Float) -> Bool {
return a =~ b || a < b
}
func <=~ (a: CGFloat, b: CGFloat) -> Bool {
return a =~ b || a < b
}
func <=~ (a: Double, b: Double) -> Bool {
return a =~ b || a < b
}
infix operator >=~ : ComparisonPrecedence
func >=~ (a: Float, b: Float) -> Bool {
return a =~ b || a > b
}
func >=~ (a: CGFloat, b: CGFloat) -> Bool {
return a =~ b || a > b
}
func >=~ (a: Double, b: Double) -> Bool {
return a =~ b || a > b
}
|
apache-2.0
|
391c20caf2b520ede65d23fbb86dd458
| 17.646154 | 54 | 0.54868 | 2.941748 | false | false | false | false |
ghysrc/EasyAttributedString
|
EasyAttributedString/EasyAttributedString.swift
|
1
|
6928
|
//
// EasyAttributedString.swift
// EasyAttributedString
//
// Created by ghysrc on 16/2/15.
// Copyright © 2016年 ghy. All rights reserved.
//
import UIKit
open class EasyAttributedStringBuilder {
open var attrString:NSMutableAttributedString!
public init(str:String) {
attrString = NSMutableAttributedString(string: str)
}
open func setNewString(_ str:String) {
attrString = NSMutableAttributedString(string: str)
}
open func range(_ range:NSRange) -> EasyAttributedStringRange {
let easr = EasyAttributedStringRange(attrString: self.attrString)
easr.range = range
return easr
}
open func rangeWith(_ location:Int, length:Int) -> EasyAttributedStringRange {
let easr = EasyAttributedStringRange(attrString: self.attrString)
easr.range = NSMakeRange(location, length)
return easr
}
open func allRange() -> EasyAttributedStringRange {
let easr = EasyAttributedStringRange(attrString: self.attrString)
easr.range = NSMakeRange(0, self.attrString.length)
return easr
}
open func firstCharacter() -> EasyAttributedStringRange {
let easr = EasyAttributedStringRange(attrString: self.attrString)
easr.range = NSMakeRange(0, 1)
return easr
}
open func rangeOfString(_ string:String) -> EasyAttributedStringRange {
let easr = EasyAttributedStringRange(attrString: self.attrString)
let nsStr = self.attrString.string as NSString
easr.range = nsStr.range(of: string)
return easr
}
open func rangeOfString(_ string:String, option:NSString.CompareOptions) -> EasyAttributedStringRange {
let easr = EasyAttributedStringRange(attrString: self.attrString)
let nsStr = self.attrString.string as NSString
easr.range = nsStr.range(of: string, options: option)
return easr
}
open func build() -> NSMutableAttributedString{
return self.attrString
}
}
open class EasyAttributedStringRange {
open var range:NSRange!
fileprivate var attrString:NSMutableAttributedString!
public init(attrString:NSMutableAttributedString) {
self.attrString = attrString
}
@discardableResult
open func setFont(_ font:UIFont) -> EasyAttributedStringRange {
attrString.addAttribute(NSFontAttributeName, value: font, range: range)
return self
}
@discardableResult
open func setFontSize(_ size:CGFloat) -> EasyAttributedStringRange {
attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: size), range: range)
return self
}
@discardableResult
open func setTextColor(_ color:UIColor) -> EasyAttributedStringRange {
attrString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
return self
}
@discardableResult
open func setBackgroundColor(_ color:UIColor) -> EasyAttributedStringRange {
attrString.addAttribute(NSBackgroundColorAttributeName, value: color, range: range)
return self
}
@discardableResult
open func setKern(_ kern:Float) -> EasyAttributedStringRange {
attrString.addAttribute(NSKernAttributeName, value: kern, range: range)
return self
}
@discardableResult
open func setLineSpacing(_ lineSpacing:CGFloat) -> EasyAttributedStringRange {
let ps = NSMutableParagraphStyle()
ps.lineSpacing = lineSpacing
attrString.addAttribute(NSParagraphStyleAttributeName, value: ps, range: range)
return self
}
@discardableResult
open func setLineSpacing(_ lineSpacing:CGFloat, alignment:NSTextAlignment) -> EasyAttributedStringRange {
let ps = NSMutableParagraphStyle()
ps.lineSpacing = lineSpacing
ps.alignment = alignment
attrString.addAttribute(NSParagraphStyleAttributeName, value: ps, range: range)
return self
}
@discardableResult
open func setParagraphStyle(_ style:NSMutableParagraphStyle) -> EasyAttributedStringRange {
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: range)
return self
}
@discardableResult
open func setUnderlineStyle(_ style:NSUnderlineStyle) -> EasyAttributedStringRange {
attrString.addAttribute(NSUnderlineStyleAttributeName, value: style.rawValue, range: range)
return self
}
@discardableResult
open func setUnderlineColor(_ color:UIColor) -> EasyAttributedStringRange {
attrString.addAttribute(NSUnderlineColorAttributeName, value: color, range: range)
return self
}
@discardableResult
open func setStrikethroughStyle(_ style:NSUnderlineStyle) -> EasyAttributedStringRange {
attrString.addAttribute(NSStrikethroughStyleAttributeName, value: style.rawValue, range: range)
return self
}
open func setStrikethroughColor(_ color:UIColor) -> EasyAttributedStringRange {
attrString.addAttribute(NSStrikethroughColorAttributeName, value: color, range: range)
return self
}
open func setStrokeColor(_ color:UIColor) -> EasyAttributedStringRange {
attrString.addAttribute(NSStrokeColorAttributeName, value: color, range: range)
return self
}
open func setStrokeWidth(_ width:Float) -> EasyAttributedStringRange {
attrString.addAttribute(NSStrokeWidthAttributeName, value: width, range: range)
return self
}
open func setShadow(_ shadow:NSShadow) -> EasyAttributedStringRange {
attrString.addAttribute(NSShadowAttributeName, value: shadow, range: range)
return self
}
open func setLigature(_ ligature:Bool) -> EasyAttributedStringRange {
attrString.addAttribute(NSLigatureAttributeName, value: ligature, range: range)
return self
}
open func setTextEffect() -> EasyAttributedStringRange {
attrString.addAttribute(NSTextEffectAttributeName, value: NSTextEffectLetterpressStyle, range: range)
return self
}
open func setBaselineOffset(_ offset:Float) -> EasyAttributedStringRange {
attrString.addAttribute(NSBaselineOffsetAttributeName, value: offset, range: range)
return self
}
open func setExpansion(_ expansion:Float) -> EasyAttributedStringRange {
attrString.addAttribute(NSExpansionAttributeName, value: expansion, range: range)
return self
}
open func setObliqueness(_ obiqueness:Float) -> EasyAttributedStringRange {
attrString.addAttribute(NSObliquenessAttributeName, value: obiqueness, range: range)
return self
}
open func setAttributes(_ attributes:[String: AnyObject]) -> EasyAttributedStringRange {
attrString.addAttributes(attributes, range: range)
return self
}
}
|
mit
|
4ccee29bede9dbfbf7de2c415fce3347
| 36.231183 | 109 | 0.700939 | 5.30245 | false | false | false | false |
google/promises
|
Sources/Promises/Promise+Then.swift
|
1
|
4565
|
// Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
public extension Promise {
typealias Then<Result> = (Value) throws -> Result
/// Creates a pending promise which eventually gets resolved with the same resolution as the
/// promise returned from `work` block. The `work` block is executed asynchronously on the given
/// `queue` only when `self` is fulfilled. If `self` is rejected, the returned promise is also
/// rejected with the same error.
/// - parameters:
/// - queue: A queue to invoke the `work` block on.
/// - work: A block to handle the value that `self` was fulfilled with.
/// - returns: A new pending promise to be resolved with the same resolution as the promise
/// returned from the `work` block.
@discardableResult
func then<Result>(
on queue: DispatchQueue = .promises,
_ work: @escaping Then<Promise<Result>>
) -> Promise<Result> {
let promise = Promise<Result>(objCPromise.__onQueue(queue, then: { objCValue in
guard let value = Promise<Value>.asValue(objCValue) else {
preconditionFailure("Cannot cast \(type(of: objCValue)) to \(Value.self)")
}
do {
return try work(value).objCPromise
} catch let error {
return error as NSError
}
}))
// Keep Swift wrapper alive for chained promise until `ObjCPromise` counterpart is resolved.
objCPromise.__addPendingObject(promise)
return promise
}
/// Creates a pending promise which eventually gets resolved with the value returned from `work`
/// block. The `work` block is executed asynchronously on the given `queue` only when `self` is
/// fulfilled. If `self` is rejected, the returned promise is also rejected with the same error.
/// - parameters:
/// - queue: A queue to invoke the `work` block on.
/// - work: A block to handle the value that `self` was fulfilled with.
/// - returns: A new pending promise to be resolved with the value returned from the `work` block.
@discardableResult
func then<Result>(
on queue: DispatchQueue = .promises,
_ work: @escaping Then<Result>
) -> Promise<Result> {
let promise = Promise<Result>(objCPromise.__onQueue(queue, then: { objCValue in
guard let value = Promise<Value>.asValue(objCValue) else {
preconditionFailure("Cannot cast \(type(of: objCValue)) to \(Value.self)")
}
do {
let value = try work(value)
return type(of: value) is NSError.Type
? value as! NSError : Promise<Result>.asAnyObject(value)
} catch let error {
return error as NSError
}
}))
// Keep Swift wrapper alive for chained promise until `ObjCPromise` counterpart is resolved.
objCPromise.__addPendingObject(promise)
return promise
}
/// Creates a pending promise which eventually gets resolved with the same resolution as `self`.
/// `work` block is executed asynchronously on the given `queue` only when `self` is fulfilled.
/// If `self` is rejected, the returned promise is also rejected with the same error.
/// - parameters:
/// - queue: A queue to invoke the `work` block on.
/// - work: A block to handle the value that `self` was fulfilled with.
/// - returns: A new pending promise to be resolved with the value passed into the `work` block.
@discardableResult
func then(
on queue: DispatchQueue = .promises,
_ work: @escaping Then<Void>
) -> Promise {
let promise = Promise(objCPromise.__onQueue(queue, then: { objCValue in
guard let value = Promise<Value>.asValue(objCValue) else {
preconditionFailure("Cannot cast \(type(of: objCValue)) to \(Value.self)")
}
do {
try work(value)
return Promise<Value>.asAnyObject(value)
} catch let error {
return error as NSError
}
}))
// Keep Swift wrapper alive for chained promise until `ObjCPromise` counterpart is resolved.
objCPromise.__addPendingObject(promise)
return promise
}
}
|
apache-2.0
|
3eee9efc6a09f8b44f62964e013da0e9
| 42.47619 | 100 | 0.681051 | 4.29445 | false | false | false | false |
riteshiosdev/iOS-UIKit
|
Advance Code/AdvancedNSOperations/Earthquakes/Operations/OperationQueue.swift
|
1
|
4882
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file contains an NSOperationQueue subclass.
*/
import Foundation
/**
The delegate of an `OperationQueue` can respond to `Operation` lifecycle
events by implementing these methods.
In general, implementing `OperationQueueDelegate` is not necessary; you would
want to use an `OperationObserver` instead. However, there are a couple of
situations where using `OperationQueueDelegate` can lead to simpler code.
For example, `GroupOperation` is the delegate of its own internal
`OperationQueue` and uses it to manage dependencies.
*/
@objc protocol OperationQueueDelegate: NSObjectProtocol {
optional func operationQueue(operationQueue: OperationQueue, willAddOperation operation: NSOperation)
optional func operationQueue(operationQueue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [NSError])
}
/**
`OperationQueue` is an `NSOperationQueue` subclass that implements a large
number of "extra features" related to the `Operation` class:
- Notifying a delegate of all operation completion
- Extracting generated dependencies from operation conditions
- Setting up dependencies to enforce mutual exclusivity
*/
class OperationQueue: NSOperationQueue {
weak var delegate: OperationQueueDelegate?
override func addOperation(operation: NSOperation) {
if let op = operation as? Operation {
// Set up a `BlockObserver` to invoke the `OperationQueueDelegate` method.
let delegate = BlockObserver(
startHandler: nil,
produceHandler: { [weak self] in
self?.addOperation($1)
},
finishHandler: { [weak self] in
if let q = self {
q.delegate?.operationQueue?(q, operationDidFinish: $0, withErrors: $1)
}
}
)
op.addObserver(delegate)
// Extract any dependencies needed by this operation.
let dependencies = op.conditions.flatMap {
$0.dependencyForOperation(op)
}
for dependency in dependencies {
op.addDependency(dependency)
self.addOperation(dependency)
}
/*
With condition dependencies added, we can now see if this needs
dependencies to enforce mutual exclusivity.
*/
let concurrencyCategories: [String] = op.conditions.flatMap { condition in
if !condition.dynamicType.isMutuallyExclusive { return nil }
return "\(condition.dynamicType)"
}
if !concurrencyCategories.isEmpty {
// Set up the mutual exclusivity dependencies.
let exclusivityController = ExclusivityController.sharedExclusivityController
exclusivityController.addOperation(op, categories: concurrencyCategories)
op.addObserver(BlockObserver { operation, _ in
exclusivityController.removeOperation(operation, categories: concurrencyCategories)
})
}
/*
Indicate to the operation that we've finished our extra work on it
and it's now it a state where it can proceed with evaluating conditions,
if appropriate.
*/
op.willEnqueue()
}
else {
/*
For regular `NSOperation`s, we'll manually call out to the queue's
delegate we don't want to just capture "operation" because that
would lead to the operation strongly referencing itself and that's
the pure definition of a memory leak.
*/
operation.addCompletionBlock { [weak self, weak operation] in
guard let queue = self, let operation = operation else { return }
queue.delegate?.operationQueue?(queue, operationDidFinish: operation, withErrors: [])
}
}
delegate?.operationQueue?(self, willAddOperation: operation)
super.addOperation(operation)
}
override func addOperations(operations: [NSOperation], waitUntilFinished wait: Bool) {
/*
The base implementation of this method does not call `addOperation()`,
so we'll call it ourselves.
*/
for operation in operations {
addOperation(operation)
}
if wait {
for operation in operations {
operation.waitUntilFinished()
}
}
}
}
|
apache-2.0
|
147ae9e8ad5600714f29c452bdbd5b2c
| 38.354839 | 137 | 0.608402 | 5.958486 | false | false | false | false |
OscarSwanros/swift
|
stdlib/public/core/ArrayBody.swift
|
4
|
2940
|
//===--- ArrayBody.swift - Data needed once per array ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Array storage begins with a Body and ends with a sequence of
// contiguous Elements. This struct describes the Body part.
//
//===----------------------------------------------------------------------===//
import SwiftShims
@_fixed_layout
@_versioned
internal struct _ArrayBody {
@_versioned
internal var _storage: _SwiftArrayBodyStorage
@_inlineable
@_versioned
internal init(
count: Int, capacity: Int, elementTypeIsBridgedVerbatim: Bool = false
) {
_sanityCheck(count >= 0)
_sanityCheck(capacity >= 0)
_storage = _SwiftArrayBodyStorage(
count: count,
_capacityAndFlags:
(UInt(truncatingIfNeeded: capacity) &<< 1) |
(elementTypeIsBridgedVerbatim ? 1 : 0))
}
/// In principle ArrayBody shouldn't need to be default
/// constructed, but since we want to claim all the allocated
/// capacity after a new buffer is allocated, it's typical to want
/// to update it immediately after construction.
@_inlineable
@_versioned
internal init() {
_storage = _SwiftArrayBodyStorage(count: 0, _capacityAndFlags: 0)
}
/// The number of elements stored in this Array.
@_inlineable
@_versioned
internal var count: Int {
get {
return _assumeNonNegative(_storage.count)
}
set(newCount) {
_storage.count = newCount
}
}
/// The number of elements that can be stored in this Array without
/// reallocation.
@_inlineable
@_versioned
internal var capacity: Int {
return Int(_capacityAndFlags &>> 1)
}
/// Is the Element type bitwise-compatible with some Objective-C
/// class? The answer is---in principle---statically-knowable, but
/// I don't expect to be able to get this information to the
/// optimizer before 1.0 ships, so we store it in a bit here to
/// avoid the cost of calls into the runtime that compute the
/// answer.
@_inlineable
@_versioned
internal var elementTypeIsBridgedVerbatim: Bool {
get {
return (_capacityAndFlags & 0x1) != 0
}
set {
_capacityAndFlags
= newValue ? _capacityAndFlags | 1 : _capacityAndFlags & ~1
}
}
/// Storage optimization: compresses capacity and
/// elementTypeIsBridgedVerbatim together.
@_inlineable
@_versioned
internal var _capacityAndFlags: UInt {
get {
return _storage._capacityAndFlags
}
set {
_storage._capacityAndFlags = newValue
}
}
}
|
apache-2.0
|
35075c3c05eb29ce6384b0acebe40d95
| 28.108911 | 80 | 0.634014 | 4.59375 | false | false | false | false |
Jamol/Nutil
|
Sources/http/HttpParser.swift
|
1
|
15181
|
//
// HttpParser.swift
// Nutil
//
// Created by Jamol Bao on 11/12/16.
// Copyright © 2015 Jamol Bao. All rights reserved.
//
import Foundation
//let kCR = "\r".utf8.map{ Int8($0) }[0]
//let kLF = "\n".utf8.map{ Int8($0) }[0]
let kCR = UInt8(ascii: "\r")
let kLF = UInt8(ascii: "\n")
let kMaxHttpHeadSize = 10*1024*1024
protocol HttpParserDelegate {
func onHttpData(data: UnsafeMutableRawPointer, len: Int)
func onHttpHeaderComplete()
func onHttpComplete()
func onHttpError(err: KMError)
}
class HttpParser : HttpHeader {
enum ReadState {
case line
case head
case body
case done
case error
}
enum ParseState {
case incomplete
case success
case failure
}
enum ChunkReadState {
case size
case data
case data_cr
case data_lf
case trailer
}
var bodyBytesRead: Int {
return totalBytesRead
}
fileprivate var totalBytesRead = 0
fileprivate var readState = ReadState.line
fileprivate var chunkState = ChunkReadState.size
fileprivate var chunkSize = 0
var delegate: HttpParserDelegate?
private var savedString = ""
fileprivate var isPaused = false
fileprivate var isUpgrade = false
var isRequest = false
var method = ""
var urlString = ""
var statusCode = 0
var version = "HTTP/1.1"
var url: URL!
override func reset() {
super.reset()
readState = .line
chunkState = .size
chunkSize = 0
totalBytesRead = 0
isPaused = false
isUpgrade = false
isRequest = false
savedString = ""
statusCode = 0
urlString = ""
}
func complete() -> Bool {
return readState == .done
}
func error() -> Bool {
return readState == .error
}
func pause() {
isPaused = true
}
func resume() {
isPaused = false
if hasBody && !isUpgrade {
readState = .body
} else {
readState = .done
onComplete()
}
}
func paused() -> Bool {
return isPaused
}
func isUpgradeTo(proto: String) -> Bool {
var str = headers[kUpgrade]
guard let upgrade = str else {
return false
}
if upgrade.caseInsensitiveCompare(proto) != .orderedSame {
return false
}
str = headers[kConnection]
guard let connection = str else {
return false
}
let tokens = connection.components(separatedBy: ",")
var hasUpgrade = false
for i in 0..<tokens.count {
var str = tokens[i]
str = str.trimmingCharacters(in: .whitespaces)
if str.caseInsensitiveCompare(kUpgrade) == .orderedSame {
hasUpgrade = true
break
}
}
if !hasUpgrade {
return false
}
if !isRequest && statusCode != 101 {
return false
}
if isRequest && proto.compare("h2c") == .orderedSame {
var hasHttp2Settings = false
for i in 0..<tokens.count {
var str = tokens[i]
str = str.trimmingCharacters(in: .whitespaces)
if str.caseInsensitiveCompare("HTTP2-Settings") == .orderedSame {
hasHttp2Settings = true
break
}
}
if !hasHttp2Settings {
return false
}
}
return true
}
func parse(data: UnsafeMutableRawPointer, len: Int) -> Int {
if readState == .done || readState == .error {
warnTrace("HttpParser::parse, invalid state: \(readState)")
return 0
}
if readState == .body && !isChunked && contentLength == nil {
// read untill EOF, return directly
totalBytesRead += len
delegate?.onHttpData(data: data, len: len)
return len
}
let bytesRead = parseHttp(data: data, len: len)
if readState == .error {
delegate?.onHttpError(err: .failed)
}
return bytesRead
}
fileprivate func parseHttp(data: UnsafeMutableRawPointer, len: Int) -> Int {
var ptr = data.assumingMemoryBound(to: UInt8.self)
var remain = len
if readState == .line {
let ret = getLine(data: ptr, len: remain)
ptr = ptr.advanced(by: ret.bytesRead)
remain -= ret.bytesRead
if var line = ret.line {
if !savedString.isEmpty {
line = savedString + line
savedString = ""
}
if !parseStartLine(line: line) {
readState = .error
return len - remain
}
readState = .head
} else {
if !saveData(data: ptr, len: remain) {
readState = .error
return len - remain
}
return len
}
}
if readState == .head {
repeat {
let ret = getLine(data: ptr, len: remain)
ptr = ptr.advanced(by: ret.bytesRead)
remain -= ret.bytesRead
if var line = ret.line {
if !savedString.isEmpty {
line = savedString + line
savedString = ""
}
if line.isEmpty { // empty line, header end
onHeaderComplete()
if isPaused {
return len - remain
}
if hasBody && !isUpgrade {
readState = .body
} else {
readState = .done
onComplete()
return len - remain
}
break
}
if !parseHeadLine(line: line) {
readState = .error
return len - remain
}
} else {
if !saveData(data: ptr, len: remain) {
readState = .error
return len - remain
}
return len
}
} while (true)
}
if readState == .body {
if isChunked {
return len - remain + parseChunk(data: ptr, len: remain)
}
if let clen = contentLength, clen - totalBytesRead <= remain {
let notifySize = clen - totalBytesRead
let notifyData = ptr
ptr = ptr.advanced(by: notifySize)
remain -= notifySize
totalBytesRead += notifySize
readState = .done
delegate?.onHttpData(data: notifyData, len: notifySize)
onComplete()
} else { // need more data or read untill EOF
if remain > 0 {
totalBytesRead += remain
delegate?.onHttpData(data: ptr, len: remain)
}
return len
}
}
return len - remain
}
fileprivate func parseStartLine(line: String) -> Bool {
let line = line.trimmingCharacters(in: .whitespaces)
let tokens = line.components(separatedBy: " ")
if tokens.count < 3 {
return false
}
let str = "HTTP/"
if str.utf8.count >= tokens[0].utf8.count {
isRequest = true
} else {
let r = Range(uncheckedBounds: (str.startIndex, str.endIndex))
isRequest = tokens[0].compare(str, options: .caseInsensitive, range: r, locale: nil) != .orderedSame
}
if isRequest {
method = tokens[0]
version = tokens[2]
if let s = tokens[1].removingPercentEncoding {
urlString = s
} else {
return false
}
url = URL(string: urlString)
if url == nil {
return false
}
} else {
version = tokens[0]
if let sc = Int(tokens[1]) {
statusCode = sc
} else {
return false
}
}
return true
}
fileprivate func parseHeadLine(line: String) -> Bool {
/*let line = line.trimmingCharacters(in: .whitespaces)
let tokens = line.components(separatedBy: ":")
if tokens.count < 2 {
return false
}
let name = tokens[0].trimmingCharacters(in: .whitespaces)
let value = tokens[1].trimmingCharacters(in: .whitespaces)
*/
let range = line.range(of: String(":"))
guard let r = range else {
return false
}
let index = line.index(before: r.upperBound)
let name = line[..<index].trimmingCharacters(in: .whitespaces)
let value = line[r.upperBound...].trimmingCharacters(in: .whitespaces)
super.addHeader(name, value)
return true
}
fileprivate func parseChunk(data: UnsafeMutablePointer<UInt8>, len: Int) -> Int {
var ptr = data
var remain = len
while remain > 0 {
switch chunkState {
case .size:
let ret = getLine(data: ptr, len: remain)
ptr = ptr.advanced(by: ret.bytesRead)
remain -= ret.bytesRead
if var line = ret.line {
if !savedString.isEmpty {
line = savedString + line
savedString = ""
}
if line.isEmpty {
readState = .error
return len - remain
}
if let cs = Int(line, radix: 16) {
chunkSize = cs
if chunkSize == 0 {
chunkState = .trailer
} else {
chunkState = .data
}
} else {
readState = .error
return len - remain
}
} else {
if !saveData(data: ptr, len: remain) {
readState = .error
return len - remain
}
return len
}
case .data:
if chunkSize <= remain {
let notifySize = chunkSize
let notifyData = ptr
ptr = ptr.advanced(by: notifySize)
remain -= notifySize
totalBytesRead += notifySize
chunkSize = 0
chunkState = .data_cr
delegate?.onHttpData(data: notifyData, len: notifySize)
} else {
totalBytesRead += remain
chunkSize -= remain
delegate?.onHttpData(data: ptr, len: remain)
return len
}
case .data_cr:
if ptr[0] != kCR {
readState = .error
return len - remain
} else {
ptr = ptr.advanced(by: 1)
remain -= 1
chunkState = .data_lf
}
case .data_lf:
if ptr[0] != kLF {
readState = .error
return len - remain
} else {
ptr = ptr.advanced(by: 1)
remain -= 1
chunkState = .size
}
case .trailer:
let ret = getLine(data: ptr, len: remain)
ptr = ptr.advanced(by: ret.bytesRead)
remain -= ret.bytesRead
if var line = ret.line {
if !savedString.isEmpty {
line = savedString + line
savedString = ""
}
if line.isEmpty {
readState = .done
onComplete()
return len - remain
}
// TODO: parse trailer
} else {
if !saveData(data: ptr, len: remain) {
readState = .error
return len - remain
}
return len
}
}
}
return len
}
fileprivate func readUntillEOF() -> Bool {
return !isRequest && contentLength == nil && !isChunked &&
!((100 <= statusCode && statusCode <= 199) ||
204 == statusCode || 304 == statusCode)
}
func setEOF() -> Bool {
if readUntillEOF() && readState == .body {
readState = .done
delegate?.onHttpComplete()
return true
}
return false
}
fileprivate func onHeaderComplete() {
if isRequest {
processHeader()
} else {
processHeader(statusCode)
}
if let clen = contentLength {
infoTrace("HttpParser, contentLength=\(clen)")
}
if isChunked {
infoTrace("HttpParser, isChunked=\(isChunked)")
}
if headers[kUpgrade] != nil {
isUpgrade = true
}
delegate?.onHttpHeaderComplete()
}
fileprivate func onComplete() {
delegate?.onHttpComplete()
}
fileprivate func saveData(data: UnsafeMutablePointer<UInt8>, len: Int) -> Bool {
if len + savedString.utf8.count > kMaxHttpHeadSize {
return false
}
let str = String(bytesNoCopy: data, length: len, encoding: .utf8, freeWhenDone: false)
if let str = str {
savedString += str
}
return true
}
fileprivate func getLine(data: UnsafeMutablePointer<UInt8>, len: Int) -> (line: String?, bytesRead: Int) {
let str = String(bytesNoCopy: data, length: len, encoding: .ascii, freeWhenDone: false)
guard let s = str else {
return (nil, 0)
}
let range = s.range(of: String("\n"))
guard let r = range else {
return (nil, 0)
}
var index = s.index(before: r.upperBound)
if s.distance(from: s.startIndex, to: index) > 0 && s[index] == "\r" {
index = s.index(before: index)
}
return (String(s[..<index]), s.distance(from: s.startIndex, to: r.upperBound) + 1)
}
}
|
mit
|
b00cd98b5560bca57ec355fdc2f94711
| 30.559252 | 112 | 0.452372 | 5.19863 | false | false | false | false |
DopamineLabs/DopamineKit-iOS
|
Example/Tests/Mocks/MockBoundlessAPIClient.swift
|
1
|
2790
|
//
// MockHTTPClient.swift
// BoundlessKit_Example
//
// Created by Akash Desai on 3/10/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
@testable import BoundlessKit
class MockBoundlessAPIClient : BoundlessAPIClient {
override init(properties: BoundlessProperties = BoundlessProperties.fromTestFile()!, session: URLSessionProtocol = MockURLSession()) {
print("Created a mock apiclient")
super.init(properties: properties, session: session)
self.version.refreshContainer = MockBKRefreshCartridgeContainer()
}
override var logRequests: Bool {
get { return true }
set { }
}
override var logResponses: Bool {
get { return true }
set { }
}
}
class MockURLSession: URLSessionProtocol {
//MARK: Mock Responses
internal var mockResponse: [URL: [String: Any]] = [:]
//MARK: Protocol Method
func send(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol {
print("Mock http request to url:\(String(describing: request.url!))")
return MockURLSessionDataTask(
request: request,
responseData: try! JSONSerialization.data(withJSONObject: mockResponse[request.url!] ?? [:]),
completion: completionHandler
)
}
}
// MARK: - Delayed Client
class MockDelayedURLSession: MockURLSession {
var delayTime: TimeInterval = 3
//MARK: Protocol Method
override func send(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol {
let task = super.send(request: request, completionHandler: completionHandler) as! MockURLSessionDataTask
task.delayTime = delayTime
return task
}
}
// MARK: - Mock URLSessionDataTaskProtocol
class MockURLSessionDataTask: URLSessionDataTaskProtocol {
let urlRequest: URLRequest
let mockResponseData: Data
let taskFinishHandler: (Data?, URLResponse?, Error?) -> Void
var delayTime: TimeInterval = 0
init(request: URLRequest, responseData: Data, completion: @escaping (Data?, URLResponse?, Error?) -> Void ) {
urlRequest = request
mockResponseData = responseData
taskFinishHandler = completion
}
func start() {
print("Did start url session data task to:<\(String(describing: urlRequest.url))> with \nrequest data:\(try! JSONSerialization.jsonObject(with: urlRequest.httpBody!)) \nmock response:<\(try! JSONSerialization.jsonObject(with: mockResponseData))> ")
DispatchQueue.global().asyncAfter(deadline: .now() + delayTime) {
self.taskFinishHandler(self.mockResponseData, URLResponse(), nil)
}
}
}
|
mit
|
c03125d11785f6771e7772a35437c0eb
| 31.811765 | 256 | 0.680889 | 4.936283 | false | false | false | false |
albertinopadin/SwiftBreakout
|
Breakout/Block.swift
|
1
|
4568
|
//
// Block.swift
// Breakout
//
// Created by Albertino Padin on 10/27/14.
// Copyright (c) 2014 Albertino Padin. All rights reserved.
//
import Foundation
import SceneKit
enum BlockColor: Int
{
case BlueColor = 1,
RedColor,
GreenColor,
GrayColor
static func numberOfColors() -> Int
{
return 4
}
}
class Block: SCNNode
{
init(color: BlockColor)
{
super.init()
self.geometry = Block.constructGeometry(color)
let blockShape = SCNPhysicsShape(geometry: self.geometry!, options: nil)
self.name = "Block"
self.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: blockShape)
self.physicsBody!.mass = 0
Block.setContactBitMasks(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class func constructGeometry(color: BlockColor) -> SCNGeometry
{
var nodeGeometry: SCNGeometry
switch color
{
case .BlueColor:
nodeGeometry = blueBlock()
case .RedColor:
nodeGeometry = redBlock()
case .GreenColor:
nodeGeometry = greenBlock()
case .GrayColor:
nodeGeometry = grayBlock()
}
return nodeGeometry
}
class func setContactBitMasks(blockNode: SCNNode)
{
blockNode.physicsBody!.categoryBitMask = 1 << 0
blockNode.physicsBody!.collisionBitMask = 1 << 0
if #available(iOS 9.0, *) {
blockNode.physicsBody!.contactTestBitMask = 1
} else {
// Fallback on earlier versions
// By default will be the same as the collisionBitMask
}
}
/* NODES */
class func blueBlockNode() -> SCNNode
{
let blueNode = SCNNode(geometry: blueBlock())
let blueShape = SCNPhysicsShape(geometry: blueBlock(), options: nil)
blueNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: blueShape)
blueNode.physicsBody!.mass = 0
return blueNode
}
class func redBlockNode() -> SCNNode
{
let redNode = SCNNode(geometry: redBlock())
let redShape = SCNPhysicsShape(geometry: redBlock(), options: nil)
redNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: redShape)
redNode.physicsBody!.mass = 0
return redNode
}
class func greenBlockNode() -> SCNNode
{
let greenNode = SCNNode(geometry: greenBlock())
let greenShape = SCNPhysicsShape(geometry: greenBlock(), options: nil)
greenNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: greenShape)
greenNode.physicsBody!.mass = 0
return greenNode
}
class func grayBlockNode() -> SCNNode
{
let grayNode = SCNNode(geometry: grayBlock())
let grayShape = SCNPhysicsShape(geometry: grayBlock(), options: nil)
grayNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: grayShape)
grayNode.physicsBody!.mass = 0
return grayNode
}
/* GEOMETRIES */
class func blueBlock() -> SCNGeometry
{
let blueBlock = SCNBox(width: 4.0, height: 2.0, length: 1.0, chamferRadius: 0.5)
blueBlock.firstMaterial!.diffuse.contents = UIColor.blueColor()
blueBlock.firstMaterial!.specular.contents = UIColor.whiteColor()
return blueBlock
}
class func redBlock() -> SCNGeometry
{
let redBlock = SCNBox(width: 4.0, height: 2.0, length: 1.0, chamferRadius: 0.5)
redBlock.firstMaterial!.diffuse.contents = UIColor.redColor()
redBlock.firstMaterial!.specular.contents = UIColor.whiteColor()
return redBlock
}
class func greenBlock() -> SCNGeometry
{
let greenBlock = SCNBox(width: 4.0, height: 2.0, length: 1.0, chamferRadius: 0.5)
greenBlock.firstMaterial!.diffuse.contents = UIColor.greenColor()
greenBlock.firstMaterial!.specular.contents = UIColor.whiteColor()
return greenBlock
}
class func grayBlock() -> SCNGeometry
{
let grayBlock = SCNBox(width: 4.0, height: 2.0, length: 1.0, chamferRadius: 0.5)
grayBlock.firstMaterial!.diffuse.contents = UIColor.lightGrayColor()
grayBlock.firstMaterial!.specular.contents = UIColor.whiteColor()
return grayBlock
}
}
|
gpl-2.0
|
a5daaaa7e59460ec76dacb71c4507742
| 28.668831 | 99 | 0.619746 | 4.568 | false | false | false | false |
rudkx/swift
|
test/Distributed/distributed_protocol_isolation.swift
|
1
|
9205
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
// REQUIRES: concurrency
// REQUIRES: distributed
import Distributed
import FakeDistributedActorSystems
/// Use the existential wrapper as the default actor system.
typealias DefaultDistributedActorSystem = FakeActorSystem
// ==== -----------------------------------------------------------------------
// MARK: Distributed actor protocols
protocol WrongDistFuncs {
distributed func notDistActor() // expected-error{{'distributed' method can only be declared within 'distributed actor'}}{{5-17=}} {{25-25=: DistributedActor}}
}
protocol DistProtocol: DistributedActor {
// FIXME(distributed): avoid issuing these warnings, these originate from the call on the DistProtocol where we marked this func as dist isolated,
func local() -> String
// (the note appears a few times, because we misuse the call many times)
// expected-note@-2{{distributed actor-isolated instance method 'local()' declared here}}
// expected-note@-3{{distributed actor-isolated instance method 'local()' declared here}}
// expected-note@-4{{distributed actor-isolated instance method 'local()' declared here}}
distributed func dist() -> String
distributed func dist(string: String) -> String
distributed func distAsync() async -> String
distributed func distThrows() throws -> String
distributed func distAsyncThrows() async throws -> String
}
distributed actor SpecificDist: DistProtocol {
nonisolated func local() -> String { "hi" }
distributed func dist() -> String { "dist!" }
distributed func dist(string: String) -> String { string }
distributed func distAsync() async -> String { "dist!" }
distributed func distThrows() throws -> String { "dist!" }
distributed func distAsyncThrows() async throws -> String { "dist!" }
func inside() async throws {
_ = self.local() // ok
_ = self.dist() // ok
_ = self.dist(string: "") // ok
_ = await self.distAsync() // ok
_ = try self.distThrows() // ok
_ = try await self.distAsyncThrows() // ok
}
}
func outside_good(dp: SpecificDist) async throws {
_ = dp.local()
_ = try await dp.dist() // implicit async throws
_ = try await dp.dist(string: "") // implicit async throws
_ = try await dp.distAsync() // implicit throws
_ = try await dp.distThrows() // implicit async
_ = try await dp.distAsyncThrows() // ok
}
func outside_good_generic<DP: DistProtocol>(dp: DP) async throws {
_ = dp.local() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}}
_ = await dp.local() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}}
// the below warning is expected because we don't apply the "implicitly async" to the not-callable func
// expected-warning@-2{{no 'async' operations occur within 'await' expression}}
_ = try dp.local() // expected-error{{only 'distributed' instance methods can be called on a potentially remote distributed actor}}
// the below warning is expected because we don't apply the "implicitly throwing" to the not-callable func
// expected-warning@-2{{no calls to throwing functions occur within 'try' expression}}
_ = try await dp.dist() // implicit async throws
_ = try await dp.dist(string: "") // implicit async throws
_ = try await dp.distAsync() // implicit throws
_ = try await dp.distThrows() // implicit async
_ = try await dp.distAsyncThrows() // ok
}
func outside_good_ext<DP: DistProtocol>(dp: DP) async throws {
_ = try await dp.dist() // implicit async throws
_ = try await dp.dist(string: "") // implicit async throws
_ = try await dp.distAsync() // implicit throws
_ = try await dp.distThrows() // implicit async
_ = try await dp.distAsyncThrows() // ok
}
// ==== ------------------------------------------------------------------------
// MARK: General protocols implemented by distributed actors
/// A distributed actor could only conform to this by making everything 'nonisolated':
protocol StrictlyLocal {
func local()
// expected-note@-1{{mark the protocol requirement 'local()' 'async throws' in order witness it with 'distributed' function declared in distributed actor 'Nope2_StrictlyLocal'}}
func localThrows() throws
// expected-note@-1{{mark the protocol requirement 'localThrows()' 'async' in order witness it with 'distributed' function declared in distributed actor 'Nope2_StrictlyLocal'}}
// TODO: localAsync
}
distributed actor Nope1_StrictlyLocal: StrictlyLocal {
func local() {}
// expected-error@-1{{actor-isolated instance method 'local()' cannot be used to satisfy a protocol requirement}}
// expected-note@-2{{add 'nonisolated' to 'local()' to make this instance method not isolated to the actor}}
func localThrows() throws {}
// expected-error@-1{{actor-isolated instance method 'localThrows()' cannot be used to satisfy a protocol requirement}}
// expected-note@-2{{add 'nonisolated' to 'localThrows()' to make this instance method not isolated to the actor}}
}
distributed actor Nope2_StrictlyLocal: StrictlyLocal {
distributed func local() {}
// expected-error@-1{{actor-isolated distributed instance method 'local()' cannot be used to satisfy a protocol requirement}}
// expected-note@-2{{add 'nonisolated' to 'local()' to make this distributed instance method not isolated to the actor}}
distributed func localThrows() throws {}
// expected-error@-1{{actor-isolated distributed instance method 'localThrows()' cannot be used to satisfy a protocol requirement}}
// expected-note@-2{{add 'nonisolated' to 'localThrows()' to make this distributed instance method not isolated to the actor}}
}
distributed actor OK_StrictlyLocal: StrictlyLocal {
nonisolated func local() {}
nonisolated func localThrows() throws {}
}
protocol Server {
func send<Message: Codable>(message: Message) async throws -> String
}
actor MyServer : Server {
func send<Message: Codable>(message: Message) throws -> String { "" } // expected-warning{{non-sendable type 'Message' in parameter of actor-isolated instance method 'send(message:)' satisfying non-isolated protocol requirement cannot cross actor boundary}}
}
protocol AsyncThrowsAll {
func maybe(param: String, int: Int) async throws -> Int
}
actor LocalOK_AsyncThrowsAll: AsyncThrowsAll {
func maybe(param: String, int: Int) async throws -> Int { 1111 }
}
actor LocalOK_Implicitly_AsyncThrowsAll: AsyncThrowsAll {
func maybe(param: String, int: Int) throws -> Int { 1111 }
}
distributed actor Nope1_AsyncThrowsAll: AsyncThrowsAll {
func maybe(param: String, int: Int) async throws -> Int { 111 }
// expected-error@-1{{distributed actor-isolated instance method 'maybe(param:int:)' cannot be used to satisfy a protocol requirement}}
}
distributed actor OK_AsyncThrowsAll: AsyncThrowsAll {
distributed func maybe(param: String, int: Int) async throws -> Int { 222 }
}
distributed actor OK_Implicitly_AsyncThrowsAll: AsyncThrowsAll {
distributed func maybe(param: String, int: Int) -> Int { 333 }
}
func testAsyncThrowsAll(p: AsyncThrowsAll,
dap: OK_AsyncThrowsAll,
dapi: OK_Implicitly_AsyncThrowsAll) async throws {
_ = try await p.maybe(param: "", int: 0)
_ = try await dap.maybe(param: "", int: 0)
_ = try await dapi.maybe(param: "", int: 0)
// Such conversion is sound:
let pp: AsyncThrowsAll = dapi
_ = try await pp.maybe(param: "", int: 0)
}
// ==== ------------------------------------------------------------------------
// MARK: Error cases
protocol ErrorCases: DistributedActor {
distributed func unexpectedAsyncThrows() -> String
// expected-note@-1{{protocol requires function 'unexpectedAsyncThrows()' with type '() -> String'; do you want to add a stub?}}
}
distributed actor BadGreeter: ErrorCases {
// expected-error@-1{{type 'BadGreeter' does not conform to protocol 'ErrorCases'}}
distributed func unexpectedAsyncThrows() async throws -> String { "" }
// expected-note@-1{{candidate is 'async', but protocol requirement is not}}
}
// ==== ------------------------------------------------------------------------
// MARK: Distributed Actor requiring protocol witnessing async throws requirements
struct Salsa: Codable, Sendable {}
protocol TacoPreparation {
func makeTacos(with salsa: Salsa) async throws
}
protocol DistributedTacoMaker: DistributedActor, TacoPreparation {
}
extension DistributedTacoMaker {
distributed func makeTacos(with: Salsa) {}
}
extension TacoPreparation {
distributed func makeSalsa() -> Salsa {}
// expected-error@-1{{'distributed' method can only be declared within 'distributed actor'}}
}
distributed actor TacoWorker: DistributedTacoMaker {} // implemented in extensions
extension DistributedTacoMaker where SerializationRequirement == Codable {
distributed func makeGreatTacos(with: Salsa) {}
}
|
apache-2.0
|
b49f2046c39628c62d1c96a3c0a491eb
| 42.625592 | 260 | 0.700489 | 4.279405 | false | false | false | false |
Vluxe/Swift-API-Project
|
Client/Client/LoginViewController.swift
|
1
|
2308
|
//
// LoginViewController.swift
// Client
//
// Created by Dalton Cherry on 10/8/14.
// Copyright (c) 2014 vluxe. All rights reserved.
//
import UIKit
public protocol LoginDelegate {
func didLogin(user: User)
}
public class LoginViewController : UIViewController {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var createButton: UIButton!
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
public var delegate: LoginDelegate?
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//the login button action
@IBAction func login(sender: UIButton) {
loginButton.enabled = false
createButton.enabled = false
User.login(nameField.text, password: passwordField.text, success: { (user: User) in
self.delegate?.didLogin(user)
self.loginButton.enabled = true
self.createButton.enabled = true
}, { (error: NSError) in
self.errorFinished(error)
})
}
//the create button action
@IBAction func create(sender: UIButton) {
loginButton.enabled = false
createButton.enabled = false
User.create(nameField.text, password: passwordField.text, imageUrl: "someurl",
success: { (user: User) in
self.delegate?.didLogin(user)
self.loginButton.enabled = true
self.createButton.enabled = true
}, { (error: NSError) in
self.errorFinished(error)
})
}
//show an alert and renable the buttons is the login or create failed
func errorFinished(error: NSError) {
println("unable to login")
self.loginButton.enabled = true
self.createButton.enabled = true
let alert = UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
|
apache-2.0
|
2d0402b377da1877b3a6dc6e62ef2416
| 31.069444 | 124 | 0.634749 | 4.758763 | false | false | false | false |
tkrajacic/SampleCodeStalker
|
SampleCodeStalker/DocumentFetcher.swift
|
1
|
1510
|
//
// DocumentFetcher.swift
// SampleCodeStalker
//
// Created by Thomas Krajacic on 23.1.2016.
// Copyright © 2016 Thomas Krajacic. All rights reserved.
//
import Foundation
struct DocumentFetcher {
let url: URL
init(url: URL) {
self.url = url
}
func fetch(_ completionHandler: @escaping (_ json: [String:AnyObject])->Void) {
let request = URLRequest(url: url, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval: 10)
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
session.dataTask(with: request) { data, response, error in
guard let data = data, let response = response as? HTTPURLResponse
, error == nil && response.statusCode == 200 else { return }
let jsonString = String(data: data, encoding: String.Encoding.utf8)!.replacingOccurrences(of: ",\n }", with: "}")
let newData = jsonString.data(using: String.Encoding.utf8)!
if let jsonData = try? JSONSerialization.jsonObject(with: newData, options: JSONSerialization.ReadingOptions.allowFragments),
let jsonDict = jsonData as? [String:AnyObject] {
completionHandler(jsonDict)
}
}.resume()
}
}
extension DocumentFetcher {
init(endpoint: AppleDocumentsAPI) {
self.url = endpoint.url
}
}
|
mit
|
a55162065efbfb99465c9b6ede109398
| 31.106383 | 137 | 0.607025 | 4.867742 | false | true | false | false |
bingoogolapple/SwiftNote-PartOne
|
保存NSString和UIImage/保存NSString和UIImage/ViewController.swift
|
1
|
4759
|
//
// ViewController.swift
// 保存NSString和UIImage
//
// Created by bingoogol on 14/8/24.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/*
需求:
从照片库读取一张照片,并且设置界面上的UIImageView
再次进入应用时,直接显示上次选择的图像
思路:
1.界面上需要一个按钮和一个UIImageView
2.使用UIImagePickerController选择照片并且设置UIImageView的显示
3.保存用户选择的UIImage
*/
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imageView:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(frame: CGRect(x: 10, y: 22, width: 300, height: 300))
imageView.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(imageView)
var button:UIButton = UIButton.buttonWithType(UIButtonType.System)
as UIButton
button.frame = CGRect(x: 50, y: 320, width: 100, height: 40)
button.setTitle("选择照片", forState: UIControlState.Normal)
button.addTarget(self, action: Selector("selectPhoto"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
// 判断文件是否存在,如果存在,加载到UIImageView中
var documents = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
println(documents[0])
var image:UIImage! = UIImage(contentsOfFile: "\(documents[0])/image.png")
if (image != nil) {
imageView.image = image
}
var strPath = "\(documents[0])/abc.txt"
var error : NSError?
var savedStr:NSString! = NSString(contentsOfFile: strPath, encoding: NSUTF8StringEncoding, error: &error)
if error != nil {
println("从文件读取字符串错误: \(error)")
}
if (savedStr != nil) {
println("savedStr=\(savedStr)")
}
}
func selectPhoto() {
println("选择照片")
var imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
self.presentViewController(imagePicker, animated: true, completion: nil)
}
// 如果one执行了,这个方法是不会执行的
// func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
// println("one")
// imageView.image = image
// picker.dismissViewControllerAnimated(true, completion: nil)
// }
// one
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!) {
//println(info)
/*
[
UIImagePickerControllerEditedImage: <UIImage: 0x7fc47a931a40> size {636, 636} orientation 0 scale 1.000000,
UIImagePickerControllerOriginalImage: <UIImage: 0x7fc47a931810> size {255, 255} orientation 0 scale 1.000000,
UIImagePickerControllerCropRect: NSRect: {{0, 0}, {255, 255}},
UIImagePickerControllerReferenceURL: assets-library://asset/asset.JPG?id=247CCD74-5C75-4701-B1AA-1B47A71D0B3D&ext=JPG,
UIImagePickerControllerMediaType: public.image
]
*/
var image:UIImage = info["UIImagePickerControllerEditedImage"] as UIImage
imageView.image = image
// 保存图像时,需要使用NSData进行中转,NSData中间可以存储任意格式的二进制数据
var imageData:NSData = UIImagePNGRepresentation(image)
var documents = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
println(documents[0])
imageData.writeToFile("\(documents[0])/image.png", atomically: true)
picker.dismissViewControllerAnimated(true, completion: nil)
// 注意:虽然NSDictionary可以直接写入文件,但是当内容包含非Boolean,Date,Number,String时,则不能直接写入文件
var strPath = "\(documents[0])/abc.txt"
// 写入NSString的演示,除非特殊原因,在ios开发中字符串的编码格式统一使用UTF-8
var string:NSString = "爱老虎油"
// NSUTF8StringEncoding在NSString中
string.writeToFile(strPath, atomically: true, encoding: NSUTF8StringEncoding, error:nil)
}
}
|
apache-2.0
|
b56b8b5496147ececfff68cc0f0a053f
| 38.796296 | 149 | 0.671631 | 4.630388 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/DiscoveryV1/Models/SourceOptions.swift
|
1
|
4509
|
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
The **options** object defines which items to crawl from the source system.
*/
public struct SourceOptions: Codable, Equatable {
/**
Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source**
object is set to `box`.
*/
public var folders: [SourceOptionsFolder]?
/**
Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the
**type** field of the **source** object is set to `salesforce`.
*/
public var objects: [SourceOptionsObject]?
/**
Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and
required when the **type** field of the **source** object is set to `sharepoint`.
*/
public var siteCollections: [SourceOptionsSiteColl]?
/**
Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the
**source** object is set to `web_crawl`.
*/
public var urls: [SourceOptionsWebCrawl]?
/**
Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the
**source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified.
*/
public var buckets: [SourceOptionsBuckets]?
/**
When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array
must not be specified.
*/
public var crawlAllBuckets: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case folders = "folders"
case objects = "objects"
case siteCollections = "site_collections"
case urls = "urls"
case buckets = "buckets"
case crawlAllBuckets = "crawl_all_buckets"
}
/**
Initialize a `SourceOptions` with member variables.
- parameter folders: Array of folders to crawl from the Box source. Only valid, and required, when the **type**
field of the **source** object is set to `box`.
- parameter objects: Array of Salesforce document object types to crawl from the Salesforce source. Only valid,
and required, when the **type** field of the **source** object is set to `salesforce`.
- parameter siteCollections: Array of Microsoft SharePointoint Online site collections to crawl from the
SharePoint source. Only valid and required when the **type** field of the **source** object is set to
`sharepoint`.
- parameter urls: Array of Web page URLs to begin crawling the web from. Only valid and required when the
**type** field of the **source** object is set to `web_crawl`.
- parameter buckets: Array of cloud object store buckets to begin crawling. Only valid and required when the
**type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is
`false` or not specified.
- parameter crawlAllBuckets: When `true`, all buckets in the specified cloud object store are crawled. If set to
`true`, the **buckets** array must not be specified.
- returns: An initialized `SourceOptions`.
*/
public init(
folders: [SourceOptionsFolder]? = nil,
objects: [SourceOptionsObject]? = nil,
siteCollections: [SourceOptionsSiteColl]? = nil,
urls: [SourceOptionsWebCrawl]? = nil,
buckets: [SourceOptionsBuckets]? = nil,
crawlAllBuckets: Bool? = nil
)
{
self.folders = folders
self.objects = objects
self.siteCollections = siteCollections
self.urls = urls
self.buckets = buckets
self.crawlAllBuckets = crawlAllBuckets
}
}
|
apache-2.0
|
a52436bf7f15588841e7cce3cdb0d5a5
| 41.140187 | 119 | 0.674872 | 4.369186 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/SupportingFiles/WatsonCredentialsGHA.swift
|
1
|
4243
|
/**
* (C) Copyright IBM Corp. 2016, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
struct WatsonCredentials {
static let AssistantAPIKey = ProcessInfo.processInfo.environment["ASSISTANT_APIKEY"] ?? "<no_apikey>"
static let AssistantUsername = "your-username-here"
static let AssistantPassword = "your-password-here"
static let AssistantURL = ProcessInfo.processInfo.environment["ASSISTANT_URL"]
static let AssistantWorkspace = "cogntive-car-sample-workspace"
static let AssistantV2Username = "your-username-here"
static let AssistantV2Password = "your-password-here"
static let AssistantV2URL = ProcessInfo.processInfo.environment["ASSISTANT_URL"]
static let AssistantV2ID = ProcessInfo.processInfo.environment["ASSISTANT_ASSISTANT_ID"]
static let AssistantV2PremiumAPIKey: String? = nil
static let AssistantV2PremiumURL: String? = nil
static let AssistantV2PremiumAssistantID: String? = nil
static let DiscoveryAPIKey = ProcessInfo.processInfo.environment["DISCOVERY_APIKEY"] ?? "<no_apikey>"
static let DiscoveryUsername = "your-username-here"
static let DiscoveryPassword = "your-password-here"
static let DiscoveryURL = ProcessInfo.processInfo.environment["DISCOVERY_URL"]
static let DiscoveryCPDToken = "your-token-here"
static let DiscoveryCPDURL = "your-url-here"
static let DiscoveryV2APIKey = ProcessInfo.processInfo.environment["DISCOVERY_V2_APIKEY"] ?? "<no_apikey>"
static let DiscoveryV2ServiceURL = ProcessInfo.processInfo.environment["DISCOVERY_V2_URL"]
static let DiscoveryV2ProjectID = ProcessInfo.processInfo.environment["DISCOVERY_V2_PROJECT_ID"]
static let DiscoveryV2CollectionID = ProcessInfo.processInfo.environment["DISCOVERY_V2_COLLECTION_ID"]
static let DiscoveryV2CPDUsername = "your-username-here"
static let DiscoveryV2CPDPassword = "your-password-here"
static let DiscoveryV2CPDURL = "your-url-here"
static let DiscoveryV2CPDServiceURL = "your-serviceurl-here"
static let DiscoveryV2CPDTestProjectID = "your-projectid-here"
static let DiscoveryV2CPDTestCollectionID = "your-collectioid-here"
static let LanguageTranslatorUsername = "your-username-here"
static let LanguageTranslatorPassword = "your-password-here"
static let LanguageTranslatorV3APIKey = ProcessInfo.processInfo.environment["LANGUAGE_TRANSLATOR_APIKEY"] ?? "<no_apikey>"
static let LanguageTranslatorV3Username = "your-username-here"
static let LanguageTranslatorV3Password = "your-password-here"
static let LanguageTranslatorV3URL = ProcessInfo.processInfo.environment["LANGUAGE_TRANSLATOR_URL"]
static let NaturalLanguageUnderstandingAPIKey = ProcessInfo.processInfo.environment["NATURAL_LANGUAGE_UNDERSTANDING_APIKEY"] ?? "<no_apikey>"
static let NaturalLanguageUnderstandingUsername = "your-username-here"
static let NaturalLanguageUnderstandingPassword = "your-password-here"
static let NaturalLanguageUnderstandingURL = ProcessInfo.processInfo.environment["NATURAL_LANGUAGE_UNDERSTANDING_URL"]
static let SpeechToTextAPIKey = ProcessInfo.processInfo.environment["SPEECH_TO_TEXT_APIKEY"] ?? "<no_apikey>"
static let SpeechToTextUsername = "your-username-here"
static let SpeechToTextPassword = "your-password-here"
static let SpeechToTextURL = ProcessInfo.processInfo.environment["SPEECH_TO_TEXT_URL"]
static let TextToSpeechAPIKey = ProcessInfo.processInfo.environment["TEXT_TO_SPEECH_APIKEY"] ?? "<no_apikey>"
static let TextToSpeechUsername = "your-username-here"
static let TextToSpeechPassword = "your-password-here"
static let TextToSpeechURL = ProcessInfo.processInfo.environment["TEXT_TO_SPEECH_URL"]
}
|
apache-2.0
|
25e914c5d752c63eb0c6f9d9c0f22ddc
| 56.337838 | 145 | 0.773981 | 4.159804 | false | false | false | false |
itouch2/LeetCode
|
LeetCode/HappyNumber.swift
|
1
|
1156
|
//
// HappyNumber.swift
// LeetCode
//
// Created by You Tu on 2017/6/8.
// Copyright © 2017年 You Tu. All rights reserved.
//
/*
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
*/
import Cocoa
class HappyNumber: NSObject {
func isHappy(_ n: Int) -> Bool {
var k = n
var value = k
var set = Set<Int>([k])
while value != 1 {
k = value
value = 0
while k > 0 {
value += Int(pow(Double(k % 10), 2))
k = k / 10
}
if set.contains(value) {
return false
}
set.insert(value)
}
return true
}
}
|
mit
|
e3bc67ccb7de4fa1b75396a56766c3d0
| 25.204545 | 353 | 0.557676 | 4.003472 | false | false | false | false |
instacrate/Subber-api
|
Sources/App/Models/VendorCustomer.swift
|
2
|
2136
|
//
// VendorCustomer.swift
// subber-api
//
// Created by Hakon Hanesand on 1/22/17.
//
//
import Foundation
import Vapor
import Fluent
final class VendorCustomer: Model, Preparation {
var id: Node?
var exists: Bool = false
let customer_id: Node?
let vendor_id: Node?
let connectAccountCustomerId: String
init(vendor: Vendor, customer: Customer, account: String) throws {
guard let vendor_id = vendor.id else {
throw Abort.custom(status: .internalServerError, message: "Missing vendor id for VendorCustomer link.")
}
guard let customer_id = customer.id else {
throw Abort.custom(status: .internalServerError, message: "Missing customer id for VendorCustomer link.")
}
self.customer_id = customer_id
self.vendor_id = vendor_id
self.connectAccountCustomerId = account
}
init(node: Node, in context: Context) throws {
id = node["id"]
customer_id = try node.extract("customer_id")
vendor_id = try node.extract("vendor_id")
connectAccountCustomerId = try node.extract("connectAccountCustomerId")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"customer_id" : customer_id,
"vendor_id" : vendor_id
]).add(objects: [
"id" : id,
"connectAccountCustomerId" : connectAccountCustomerId
])
}
static func prepare(_ database: Database) throws {
try database.create(self.entity) { vendorCustomer in
vendorCustomer.id()
vendorCustomer.parent(Customer.self)
vendorCustomer.parent(Vendor.self)
vendorCustomer.string("connectAccountCustomerId")
}
}
static func revert(_ database: Database) throws {
try database.delete(self.entity)
}
}
extension VendorCustomer {
func vendor() throws -> Parent<Vendor> {
return try parent(vendor_id)
}
func customer() throws -> Parent<Customer> {
return try parent(customer_id)
}
}
|
mit
|
c65d5e9e88fce118e0eb7b7d5ec4a520
| 27.105263 | 117 | 0.611891 | 4.315152 | false | false | false | false |
Liangxue/DY-
|
DYZB/DYZB/Classes/Main/View/RecommendViewController.swift
|
1
|
4678
|
//
// RecommendViewController.swift
// DYZB
//
// Created by xue on 2017/4/11.
// Copyright © 2017年 liangxue. All rights reserved.
//
import UIKit
import Alamofire
private let kItemMargin:CGFloat = 10
private let kItemW = (kScreenW - 3*kItemMargin)/2
private let kItemH = kItemW * 0.75
private let kPrettyItemH = kItemW * 4/3
private let recommendNormalCellReuseIdentifier = "recommendNormalCellReuseIdentifier"
private let headerViewReuseIdentifier = "headerViewReuseIdentifier"
private let prettyCellReuseIdentifier = "CollectionViewPrettyCellReuseIdentifier"
private let headerViewH:CGFloat = 60
class RecommendViewController: UIViewController {
//
lazy var collectionView:UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: kItemMargin, right: kItemMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: headerViewH)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: recommendNormalCellReuseIdentifier)
collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier: prettyCellReuseIdentifier)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewReuseIdentifier)
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
collectionView.backgroundColor = UIColor.white
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
setupRecommendUI()
NetWorkTools.requestDataWithGet(URLString: "https://httpbin.org/get", parameters: nil) { (json) in
print("JSON: \(json)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension RecommendViewController{
func setupRecommendUI(){
view.addSubview(collectionView)
}
}
extension RecommendViewController:UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerV = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewReuseIdentifier, for: indexPath)
headerV.backgroundColor = UIColor.white
return headerV
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 8
}else{
return 4
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell : UICollectionViewCell!
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: prettyCellReuseIdentifier, for: indexPath)
}else{
cell = collectionView.dequeueReusableCell(withReuseIdentifier: recommendNormalCellReuseIdentifier, for: indexPath)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kItemH)
}
}
extension RecommendViewController:UICollectionViewDataSource{
}
|
mit
|
94db8d5f6d1e5fc6d72e725a055197f5
| 29.960265 | 198 | 0.687059 | 6.275168 | false | false | false | false |
eswick/StreamKit
|
Sources/IOStream.swift
|
1
|
4050
|
#if os(Linux)
import Glibc
#else
import Darwin
#endif
public let stdout = IOStream(fileDescriptor: STDOUT_FILENO, canRead: false)
public let stdin = IOStream(fileDescriptor: STDIN_FILENO, canWrite: false)
public let stderr = IOStream(fileDescriptor: STDERR_FILENO, canRead: false)
public class IOStream: Stream {
public let canRead: Bool
public let canWrite: Bool
public let canSeek: Bool
public let canTimeout: Bool
public var position: Int64 {
get {
return Int64(lseek(fileDescriptor, 0, SEEK_CUR))
}
}
public var readTimeout: UInt = 0
public var writeTimeout: UInt = 0
public let fileDescriptor: Int32
public init(fileDescriptor: Int32, canRead: Bool = true, canWrite: Bool = true, canTimeout: Bool = true, canSeek: Bool = true) {
self.fileDescriptor = fileDescriptor
self.canRead = canRead
self.canWrite = canWrite
self.canTimeout = canTimeout
self.canSeek = canSeek
}
public func read(count: Int64) throws -> [UInt8] {
if !canRead {
throw StreamError.ReadFailed(0)
}
if (readTimeout != 0 && canTimeout) {
var fds = [pollfd(fd: fileDescriptor, events: Int16(POLLIN), revents: 0)]
let pollRes = poll(&fds, 1, Int32(readTimeout))
if pollRes == 0 {
throw StreamError.TimedOut
} else if pollRes == -1 {
throw StreamError.ReadFailed(Int(errno))
}
}
var bytes = [UInt8]()
for _ in 0...count {
bytes.append(0)
}
#if os(Linux)
let bytesRead = Glibc.read(fileDescriptor, &bytes, Int(count))
#else
let bytesRead = Darwin.read(fileDescriptor, &bytes, Int(count))
#endif
if bytesRead == -1 {
throw StreamError.ReadFailed(Int(errno))
}
if bytesRead == 0 {
throw StreamError.Closed
}
return [UInt8](bytes.prefix(bytesRead))
}
public func write(bytes: [UInt8]) throws -> Int {
if !canWrite {
throw StreamError.WriteFailed(0)
}
if (writeTimeout != 0 && canTimeout) {
var fds = [pollfd(fd: fileDescriptor, events: Int16(POLLOUT), revents: 0)]
let pollRes = poll(&fds, 1, Int32(writeTimeout))
if pollRes == 0 {
throw StreamError.TimedOut
} else if pollRes == -1 {
throw StreamError.ReadFailed(Int(errno))
}
}
#if os(Linux)
let bytesWritten = Glibc.write(fileDescriptor, bytes, bytes.count)
#else
let bytesWritten = Darwin.write(fileDescriptor, bytes, bytes.count)
#endif
if bytesWritten == -1 {
throw StreamError.WriteFailed(Int(errno))
}
return bytesWritten
}
public func seek(offset: Int64, origin: SeekOrigin) throws {
if !canSeek {
throw StreamError.SeekFailed(0)
}
var seekOrigin: Int32
switch origin {
case .Beginning:
seekOrigin = SEEK_SET
case .Current:
seekOrigin = SEEK_CUR
case .End:
seekOrigin = SEEK_END
}
#if os(Linux)
let result = lseek(fileDescriptor, __off_t(offset), seekOrigin)
#else
let result = lseek(fileDescriptor, offset, seekOrigin)
#endif
if result == -1 {
throw StreamError.SeekFailed(Int(errno))
}
}
public func close() throws {
#if os(Linux)
let result = Glibc.close(fileDescriptor)
#else
let result = Darwin.close(fileDescriptor)
#endif
if result == -1 {
throw StreamError.CloseFailed(Int(errno))
}
}
}
|
mit
|
b5a37911cc2f7b7845b5a0b392220cf7
| 27.528169 | 132 | 0.534815 | 4.48505 | false | false | false | false |
ForrestAlfred/firefox-ios
|
Client/Frontend/Settings/SettingsTableViewController.swift
|
3
|
32687
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Account
import Base32
import Shared
import UIKit
private var ShowDebugSettings: Bool = false
private var DebugSettingsClickCount: Int = 0
// A base TableViewCell, to help minimize initialization and allow recycling.
class SettingsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
indentationWidth = 0
layoutMargins = UIEdgeInsetsZero
// So that the seperator line goes all the way to the left edge.
separatorInset = UIEdgeInsetsZero
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting {
private var _title: NSAttributedString?
// The title shown on the pref
var title: NSAttributedString? { return _title }
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .Subtitle }
var accessoryType: UITableViewCellAccessoryType { return .None }
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(cell: UITableViewCell) {
cell.detailTextLabel?.attributedText = status
cell.textLabel?.attributedText = title
cell.accessoryType = accessoryType
cell.accessoryView = nil
}
// Called when the pref is tapped.
func onClick(navigationController: UINavigationController?) { return }
init(title: NSAttributedString? = nil) {
self._title = title
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection : Setting {
private let children: [Setting]
init(title: NSAttributedString? = nil, children: [Setting]) {
self.children = children
super.init(title: title)
}
var count: Int {
var count = 0
for setting in children {
if !setting.hidden {
count++
}
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children {
if !setting.hidden {
if i == val {
return setting
}
i++
}
}
return nil
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
private class AccountSetting: Setting, FxAContentViewControllerDelegate {
let settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var accessoryType: UITableViewCellAccessoryType { return .None }
func contentViewControllerDidSignIn(viewController: FxAContentViewController, data: JSON) -> Void {
if data["keyFetchToken"].asString == nil || data["unwrapBKey"].asString == nil {
// The /settings endpoint sends a partial "login"; ignore it entirely.
NSLog("Ignoring didSignIn with keyFetchToken or unwrapBKey missing.")
return
}
// TODO: Error handling.
let account = FirefoxAccount.fromConfigurationAndJSON(profile.accountConfiguration, data: data)!
settings.profile.setAccount(account)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.SELrefresh()
settings.navigationController?.popToRootViewControllerAnimated(true)
}
func contentViewControllerDidCancel(viewController: FxAContentViewController) {
NSLog("didCancel")
settings.navigationController?.popToRootViewControllerAnimated(true)
}
}
private class WithAccountSetting: AccountSetting {
override var hidden: Bool { return profile.getAccount() == nil }
}
private class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.getAccount() != nil }
}
// Sync setting for connecting a Firefox Account. Shown when we don't have an account.
private class ConnectSetting: WithoutAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Sign in", comment: "Text message / button in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
viewController.url = settings.profile.accountConfiguration.signInURL
navigationController?.pushViewController(viewController, animated: true)
}
}
// Sync setting for disconnecting a Firefox Account. Shown when we have an account.
private class DisconnectSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType { return .None }
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Log Out", comment: "Button in settings screen to disconnect from your account"), attributes: [NSForegroundColorAttributeName: UIConstants.DestructiveRed])
}
override func onClick(navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: NSLocalizedString("Log Out?", comment: "Title of the 'log out firefox account' alert"),
message: NSLocalizedString("Firefox will stop syncing with your account, but won’t delete any of your browsing data on this device.", comment: "Text of the 'log out firefox account' alert"),
preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel button in the 'log out firefox account' alert"), style: .Cancel) { (action) in
// Do nothing.
})
alertController.addAction(
UIAlertAction(title: NSLocalizedString("Log Out", comment: "Disconnect button in the 'log out firefox account' alert"), style: .Destructive) { (action) in
self.settings.profile.removeAccount()
// Refresh, to show that we no longer have an Account immediately.
self.settings.SELrefresh()
})
navigationController?.presentViewController(alertController, animated: true, completion: nil)
}
}
// Sync setting that shows the current Firefox Account status.
private class AccountStatusSetting: WithAccountSetting {
override var accessoryType: UITableViewCellAccessoryType {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
// We link to the resend verification email page.
return .DisclosureIndicator
case .NeedsPassword:
// We link to the re-enter password page.
return .DisclosureIndicator
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return .None
}
}
return .DisclosureIndicator
}
override var title: NSAttributedString? {
if let account = profile.getAccount() {
return NSAttributedString(string: account.email, attributes: [NSFontAttributeName: UIConstants.DefaultStandardFontBold, NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
return nil
}
override var status: NSAttributedString? {
if let account = profile.getAccount() {
switch account.actionNeeded {
case .None:
return nil
case .NeedsVerification:
return NSAttributedString(string: NSLocalizedString("Verify your email address.", comment: "Text message in the settings table view"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
case .NeedsPassword:
let string = NSLocalizedString("Enter your password to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: count(string))
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
case .NeedsUpgrade:
let string = NSLocalizedString("Upgrade Firefox to connect.", comment: "Text message in the settings table view")
let range = NSRange(location: 0, length: count(string))
let orange = UIColor(red: 255.0 / 255, green: 149.0 / 255, blue: 0.0 / 255, alpha: 1)
let attrs : [NSObject : AnyObject]? = [NSForegroundColorAttributeName : orange]
let res = NSMutableAttributedString(string: string)
res.setAttributes(attrs, range: range)
return res
}
}
return nil
}
override func onClick(navigationController: UINavigationController?) {
let viewController = FxAContentViewController()
viewController.delegate = self
if let account = profile.getAccount() {
switch account.actionNeeded {
case .NeedsVerification:
let cs = NSURLComponents(URL: account.configuration.settingsURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .NeedsPassword:
let cs = NSURLComponents(URL: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false)
cs?.queryItems?.append(NSURLQueryItem(name: "email", value: account.email))
viewController.url = cs?.URL
case .None, .NeedsUpgrade:
// In future, we'll want to link to /settings and an upgrade page, respectively.
return
}
}
navigationController?.pushViewController(viewController, animated: true)
}
}
// For great debugging!
private class RequirePasswordDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsPassword {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeSeparated()
settings.tableView.reloadData()
}
}
// For great debugging!
private class RequireUpgradeDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() where account.actionNeeded != FxAActionNeeded.NeedsUpgrade {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.makeDoghouse()
settings.tableView.reloadData()
}
}
// For great debugging!
private class ForgetSyncAuthStateDebugSetting: WithAccountSetting {
override var hidden: Bool {
if !ShowDebugSettings {
return true
}
if let account = profile.getAccount() {
return false
}
return true
}
override var title: NSAttributedString? {
return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
profile.getAccount()?.syncAuthState.invalidate()
settings.tableView.reloadData()
}
}
// Show the current version of Firefox
private class VersionSetting : Setting {
let settings: SettingsTableViewController
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override var title: NSAttributedString? {
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String
return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])
}
override func onClick(navigationController: UINavigationController?) {
if AppConstants.BuildChannel != .Aurora {
DebugSettingsClickCount += 1
if DebugSettingsClickCount >= 5 {
DebugSettingsClickCount = 0
ShowDebugSettings = !ShowDebugSettings
settings.tableView.reloadData()
}
}
}
}
// Opens the the license page in a new tab
private class LicenseAndAcknowledgementsSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: WebServer.sharedInstance.URLForResource("license", module: "about")) {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
// Opens the on-boarding screen again
private class ShowIntroductionSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
appDelegate.browserViewController.presentIntroViewController(force: true)
}
})
}
}
// Opens the the SUMO page in a new tab
private class OpenSupportPageSetting: Setting {
init() {
super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
navigationController?.dismissViewControllerAnimated(true, completion: {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
let rootNavigationController = appDelegate.rootViewController
rootNavigationController.popViewControllerAnimated(true)
if let url = NSURL(string: "https://support.mozilla.org/products/ios") {
appDelegate.browserViewController.openURLInNewTab(url)
}
}
})
}
}
class UseCompactTabLayoutSetting: Setting {
let profile: Profile
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Use Compact Tabs", comment: "Setting to enable compact tabs in the tab overview"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = profile.prefs.boolForKey("CompactTabLayout") ?? true
cell.accessoryView = control
}
@objc func switchValueChanged(control: UISwitch) {
profile.prefs.setBool(control.on, forKey: "CompactTabLayout")
}
}
// Opens the search settings pane
private class SearchSetting: Setting {
let profile: Profile
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) }
init(settings: SettingsTableViewController) {
self.profile = settings.profile
super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let viewController = SearchSettingsTableViewController()
viewController.model = profile.searchEngines
navigationController?.pushViewController(viewController, animated: true)
}
}
private class ClearPrivateDataSetting: Setting {
let profile: Profile
var tabManager: TabManager!
init(settings: SettingsTableViewController) {
self.profile = settings.profile
self.tabManager = settings.tabManager
let clearTitle = NSLocalizedString("Clear Private Data", comment: "Label used as an item in Settings. When touched it will open a dialog prompting the user to make sure they want to clear all of their private data.")
super.init(title: NSAttributedString(string: clearTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]))
}
override func onClick(navigationController: UINavigationController?) {
let clearable = EverythingClearable(profile: profile, tabmanager: tabManager)
var title: String { return NSLocalizedString("Clear Everything", tableName: "ClearPrivateData", comment: "Title of the Clear private data dialog.") }
var message: String { return NSLocalizedString("Are you sure you want to clear all of your data? This will also close all open tabs.", tableName: "ClearPrivateData", comment: "Message shown in the dialog prompting users if they want to clear everything") }
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let clearString = NSLocalizedString("Clear", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to Clear private data dialog")
alert.addAction(UIAlertAction(title: clearString, style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in
clearable.clear() >>== { NSNotificationCenter.defaultCenter().postNotificationName(NotificationPrivateDataCleared, object: nil) }
}))
let cancelString = NSLocalizedString("Cancel", tableName: "ClearPrivateData", comment: "Used as a button label in the dialog to cancel clear private data dialog")
alert.addAction(UIAlertAction(title: cancelString, style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in }))
navigationController?.presentViewController(alert, animated: true) { () -> Void in }
}
}
private class PopupBlockingSettings: Setting {
let prefs: Prefs
let tabManager: TabManager!
let prefKey = "blockPopups"
init(settings: SettingsTableViewController) {
self.prefs = settings.profile.prefs
self.tabManager = settings.tabManager
let title = NSLocalizedString("Block Pop-up Windows", comment: "Block pop-up windows setting")
super.init(title: NSAttributedString(string: title))
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.addTarget(self, action: "switchValueChanged:", forControlEvents: UIControlEvents.ValueChanged)
control.on = prefs.boolForKey(prefKey) ?? true
cell.accessoryView = control
}
@objc func switchValueChanged(toggle: UISwitch) {
prefs.setObject(toggle.on, forKey: prefKey)
}
}
// The base settings view controller.
class SettingsTableViewController: UITableViewController {
private let Identifier = "CellIdentifier"
private let SectionHeaderIdentifier = "SectionHeaderIdentifier"
private var settings = [SettingSection]()
var profile: Profile!
var tabManager: TabManager!
override func viewDidLoad() {
super.viewDidLoad()
let privacyTitle = NSLocalizedString("Privacy", comment: "Privacy section title")
let accountDebugSettings: [Setting]
if AppConstants.BuildChannel != .Aurora {
accountDebugSettings = [
// Debug settings:
RequirePasswordDebugSetting(settings: self),
RequireUpgradeDebugSetting(settings: self),
ForgetSyncAuthStateDebugSetting(settings: self),
]
} else {
accountDebugSettings = []
}
var generalSettings = [
SearchSetting(settings: self),
PopupBlockingSettings(settings: self),
]
// There is nothing to show in the Customize section if we don't include the compact tab layout
// setting on iPad. When more options are added that work on both device types, this logic can
// be changed.
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
generalSettings += [UseCompactTabLayoutSetting(settings: self)]
}
settings += [
SettingSection(title: nil, children: [
// Without a Firefox Account:
ConnectSetting(settings: self),
// With a Firefox Account:
AccountStatusSetting(settings: self),
] + accountDebugSettings),
SettingSection(title: NSAttributedString(string: NSLocalizedString("General", comment: "General settings section title")), children: generalSettings)
]
settings += [
SettingSection(title: NSAttributedString(string: privacyTitle), children: [
ClearPrivateDataSetting(settings: self)
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("Support", comment: "Support section title")), children: [
ShowIntroductionSetting(settings: self),
OpenSupportPageSetting()
]),
SettingSection(title: NSAttributedString(string: NSLocalizedString("About", comment: "About settings section title")), children: [
VersionSetting(settings: self),
LicenseAndAcknowledgementsSetting(),
DisconnectSetting(settings: self)
])
]
navigationItem.title = NSLocalizedString("Settings", comment: "Settings")
navigationItem.leftBarButtonItem = UIBarButtonItem(
title: NSLocalizedString("Done", comment: "Done button on left side of the Settings view controller title bar"),
style: UIBarButtonItemStyle.Done,
target: navigationController, action: "SELdone")
tableView.registerClass(SettingsTableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.registerClass(SettingsTableSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = SettingsTableFooterView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 128))
tableView.separatorColor = UIConstants.TableViewSeparatorColor
tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SELrefresh()
}
@objc private func SELrefresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
// Add the refresh control right away.
if refreshControl == nil {
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "SELrefresh", forControlEvents: UIControlEvents.ValueChanged)
}
refreshControl?.beginRefreshing()
account.advance().upon { _ in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
} else {
// Remove the refresh control immediately after ending the refresh.
refreshControl?.endRefreshing()
if let refreshControl = self.refreshControl {
refreshControl.removeFromSuperview()
}
refreshControl = nil
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
var cell: UITableViewCell!
if let status = setting.status {
// Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell.
// I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account.
// Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it.
cell = SettingsTableViewCell(style: setting.style, reuseIdentifier: nil)
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell
}
setting.onConfigureCell(cell)
return cell
}
return tableView.dequeueReusableCellWithIdentifier(Identifier, forIndexPath: indexPath) as! UITableViewCell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return settings.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderIdentifier) as! SettingsTableSectionHeaderView
let section = settings[section]
if let sectionTitle = section.title?.string {
headerView.titleLabel.text = sectionTitle.uppercaseString
}
return headerView
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// empty headers should be 13px high, but headers with text should be 44
var height: CGFloat = 13
let section = settings[section]
if let sectionTitle = section.title {
if sectionTitle.length > 0 {
height = 44
}
}
return height
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
setting.onClick(navigationController)
}
return nil
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0 && indexPath.row == 0) { return 64 } //make account/sign-in row taller, as per design specs
return 44
}
}
class SettingsTableFooterView: UITableViewHeaderFooterView {
var logo: UIImageView = {
var image = UIImageView(image: UIImage(named: "settingsFlatfox"))
image.contentMode = UIViewContentMode.Center
return image
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
var topBorder = UIView(frame: CGRect(x: 0, y: 0, width: frame.width, height: 0.5))
topBorder.backgroundColor = UIConstants.TableViewSeparatorColor
addSubview(topBorder)
addSubview(logo)
logo.snp_makeConstraints { (make) -> Void in
make.centerY.centerX.equalTo(self)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SettingsTableSectionHeaderView: UITableViewHeaderFooterView {
var titleLabel: UILabel = {
var headerLabel = UILabel()
var frame = headerLabel.frame
frame.origin.x = 15
frame.origin.y = 25
headerLabel.frame = frame
headerLabel.textColor = UIConstants.TableViewHeaderTextColor
headerLabel.font = UIFont.systemFontOfSize(12.0, weight: UIFontWeightRegular)
return headerLabel
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor
addSubview(titleLabel)
self.clipsToBounds = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let topBorder = CALayer()
topBorder.frame = CGRectMake(0.0, 0.0, rect.size.width, 0.5)
topBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
layer.addSublayer(topBorder)
let bottomBorder = CALayer()
bottomBorder.frame = CGRectMake(0.0, rect.size.height - 0.5, rect.size.width, 0.5)
bottomBorder.backgroundColor = UIConstants.SeparatorColor.CGColor
layer.addSublayer(bottomBorder)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.sizeToFit()
}
}
|
mpl-2.0
|
e79e38c3716cea17c9acdb3e0dca0dad
| 41.837484 | 268 | 0.679302 | 5.716159 | false | false | false | false |
xocialize/Kiosk
|
kiosk/HttpResponse.swift
|
1
|
3911
|
//
// HttpResponse.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
enum HttpResponseBody {
case JSON(AnyObject)
case XML(AnyObject)
case PLIST(AnyObject)
case HTML(String)
case RAW(String)
func data() -> String? {
switch self {
case .JSON(let object):
if NSJSONSerialization.isValidJSONObject(object) {
var serializationError: NSError?
if let json = NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted, error: &serializationError) {
if let nsString = NSString(data: json, encoding: NSUTF8StringEncoding) {
return nsString as String
}
}
return "Serialisation error: \(serializationError)"
}
return "Invalid object to serialise."
case .XML(let data):
return "XML serialization not supported."
case .PLIST(let object):
let format = NSPropertyListFormat.XMLFormat_v1_0
if NSPropertyListSerialization.propertyList(object, isValidForFormat: format) {
var serializationError: NSError?
if let plist = NSPropertyListSerialization.dataWithPropertyList(object, format: format, options: 0, error: &serializationError) {
if let nsString = NSString(data: plist, encoding: NSUTF8StringEncoding) {
return nsString as String
}
}
return "Serialisation error: \(serializationError)"
}
return "Invalid object to serialise."
case .RAW(let body):
return body
case .HTML(let body):
return "<html><body>\(body)</body></html>"
}
}
}
enum HttpResponse {
case OK(HttpResponseBody), Created, Accepted
case MovedPermanently(String)
case BadRequest, Unauthorized, Forbidden, NotFound
case InternalServerError
case RAW(Int, NSData)
func statusCode() -> Int {
switch self {
case .OK(_) : return 200
case .Created : return 201
case .Accepted : return 202
case .MovedPermanently : return 301
case .BadRequest : return 400
case .Unauthorized : return 401
case .Forbidden : return 403
case .NotFound : return 404
case .InternalServerError : return 500
case .RAW(let code, _) : return code
}
}
func reasonPhrase() -> String {
switch self {
case .OK(_) : return "OK"
case .Created : return "Created"
case .Accepted : return "Accepted"
case .MovedPermanently : return "Moved Permanently"
case .BadRequest : return "Bad Request"
case .Unauthorized : return "Unauthorized"
case .Forbidden : return "Forbidden"
case .NotFound : return "Not Found"
case .InternalServerError : return "Internal Server Error"
case .RAW(_,_) : return "Custom"
}
}
func headers() -> [String: String] {
var headers = [String:String]()
headers["Server"] = "Swifter"
switch self {
case .MovedPermanently(let location) : headers["Location"] = location
default:[]
}
return headers
}
func body() -> NSData? {
switch self {
case .OK(let body) : return body.data()?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
case .RAW(_, let data) : return data
default : return nil
}
}
}
|
mit
|
5af8745323b3333a31387a5d4c78fcb7
| 34.225225 | 151 | 0.546292 | 5.298103 | false | false | false | false |
mlilback/MJLCommon
|
Sources/MJLCommon/extensions/Set+MJL+update.swift
|
1
|
2220
|
//
// Set+MJL+update.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
public extension Set where Element: AnyObject {
/// Given:
/// * a value type `Value`
/// * a wrapper type `Wrapper`
/// * `Wrapper` has a property of type `Value` (reached via valueKeyPath)
/// * `Value` has a property of type `T` that uniquely identifies `Value` objects (reached via uniqueKeyPath)
///
/// Process the wrappers returning a tuple of:
/// * a replacement for wrappers with updates optionally pplied and wrappers removed that didn't have a matching newValue
/// * the subset of newValues that need to have `Wrapper`s created and added to updated
/// * the subset of objects removed from wrappers
///
/// - Parameters:
/// - wrappers: A set of Wrapper objects
/// - newValues: An array of wrapped objects to update the wrappers set with
/// - valueKeyPath: The keyPath of the Wrapper to a property of type Value
/// - uniqueKeyPath: A unique property of Value to match wrappers to newValues
/// - performUpdate: If true, actually update the wrapper's valueKeyPath with the newValue
/// - Returns: A tuple of: Values that should be added, wrappers that should be removed, and wrappers that should remain (with updates applied)
func filterForUpdate<Value: Equatable, T: Equatable>(
newValues: [Value],
valueKeyPath: ReferenceWritableKeyPath<Element, Value>,
uniqueKeyPath: KeyPath<Value, T>,
performUpdate: Bool
) -> (updated: Set<Element>, added: [Value], removed: Set<Element>)
{
var added = [Value]()
var keeping = Set<Element>()
// make a copy of wrappers we can remove objects from as they are matched
var remaining = self
newValues.forEach { aValue in
let fullKeyPath = valueKeyPath.appending(path: uniqueKeyPath)
if let oldValue = first(where: {
let v1 = $0[keyPath: fullKeyPath]
let v2 = aValue[keyPath: uniqueKeyPath]
return v1 == v2
})
{
if performUpdate {
oldValue[keyPath: valueKeyPath] = aValue
}
keeping.insert(oldValue)
remaining.remove(oldValue)
} else {
added.append(aValue)
}
}
return (updated: keeping, added: added, removed: remaining)
}
}
|
isc
|
c2b62f9ab48c54da7c906457846aa64d
| 36.610169 | 144 | 0.700766 | 3.77381 | false | false | false | false |
jasonwedepohl/udacity-ios-on-the-map
|
On The Map/On The Map/StudentRecord.swift
|
1
|
901
|
//
// StudentLocation.swift
// On The Map
//
// Created by Jason Wedepohl on 2017/09/21.
//
import Foundation
struct StudentRecord {
let createdAt: String
let firstName: String
let lastName: String
let latitude: Double
let longitude: Double
let mapString: String
let mediaURL: String
let objectId: String
let uniqueKey: String
let updatedAt: String
init(_ studentRecordResponse: ParseClient.StudentRecordResponse) {
createdAt = studentRecordResponse.createdAt!
firstName = studentRecordResponse.firstName!
lastName = studentRecordResponse.lastName!
latitude = studentRecordResponse.latitude!
longitude = studentRecordResponse.longitude!
mapString = studentRecordResponse.mapString!
mediaURL = studentRecordResponse.mediaURL!
objectId = studentRecordResponse.objectId!
uniqueKey = studentRecordResponse.uniqueKey!
updatedAt = studentRecordResponse.updatedAt!
}
}
|
mit
|
6577172e4decb29dd7013304a648e7a2
| 25.5 | 67 | 0.788013 | 4.230047 | false | false | false | false |
ozpopolam/TrivialAsia
|
TrivialAsia/TriviaColor.swift
|
1
|
1414
|
//
// TriviaColor.swift
// TrivialAsia
//
// Created by Anastasia Stepanova-Kolupakhina on 28.05.17.
// Copyright © 2017 Anastasia Kolupakhina. All rights reserved.
//
import UIKit
enum TriviaColor {
static let whiteSmoke = UIColor(red: 236.0 / 255.0,
green: 236.0 / 255.0,
blue: 236.0 / 255.0,
alpha: 1.0)
static let pink = UIColor(red: 255.0 / 255.0,
green: 45.0 / 255.0,
blue: 85.0 / 255.0,
alpha: 1.0)
static let tealBlue = UIColor(red: 90.0 / 255.0,
green: 200.0 / 255.0,
blue: 250.0 / 255.0,
alpha: 1.0)
static let blue = UIColor(red: 0.0 / 255.0,
green: 122.0 / 255.0,
blue: 255.0 / 255.0,
alpha: 1.0)
static let green = UIColor(red: 76.0 / 255.0,
green: 217.0 / 255.0,
blue: 100.0 / 255.0,
alpha: 1.0)
static let red = UIColor(red: 255.0 / 255.0,
green: 59.0 / 255.0,
blue: 59.0 / 255.0,
alpha: 1.0)
}
|
mit
|
9866f4ac613f4fb69192832b4c2a9e5d
| 32.642857 | 64 | 0.374381 | 4.180473 | false | false | false | false |
lieyunye/WeixinWalk
|
微信运动/微信运动/HealthManager.swift
|
2
|
4246
|
//
// HealthManager.swift
// 微信运动
//
// Created by Eular on 9/5/15.
// Copyright © 2015 Eular. All rights reserved.
//
import UIKit
import HealthKit
class HealthManager: NSObject {
let healthKitStore = HKHealthStore()
func authorizeHealthKit(completion: ((success: Bool, error: NSError?) -> Void)!) {
let healthKitTypesToWrite: Set = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!,
]
let healthKitTypesToRead: Set = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!,
]
if !HKHealthStore.isHealthDataAvailable() {
let error = NSError(domain: "com.eular.weixinwalk", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in this Device"])
if completion != nil {
completion(success: false, error: error)
}
return
}
healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in
if completion != nil {
completion(success: success, error: error)
}
}
}
func saveStepsSample(steps: Double, endDate: NSDate, duration: Int, completion: ( (Bool, NSError!) -> Void)!) {
let sampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let stepsQuantity = HKQuantity(unit: HKUnit.countUnit(), doubleValue: steps)
let startDate = endDate.dateByAddingTimeInterval(0 - 60 * Double(duration))
let stepsSample = HKQuantitySample(type: sampleType!, quantity: stepsQuantity, startDate: startDate, endDate: endDate)
self.healthKitStore.saveObject(stepsSample, withCompletion: { (success, error) -> Void in
completion(success, error)
})
}
func readStepsWorksout(limit: Int, completion: (([AnyObject]!, NSError!) -> Void)!) {
let sampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let predicate = HKQuery.predicateForObjectsFromSource(HKSource.defaultSource())
let sampleQuery = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: limit, sortDescriptors: [sortDescriptor])
{ (sampleQuery, results, error ) -> Void in
if let queryError = error {
print( "There was an error while reading the samples: \(queryError.localizedDescription)")
}
completion(results, error)
}
healthKitStore.executeQuery(sampleQuery)
}
func readTotalSteps(completion: ((Int) -> Void)) {
let endDate = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let startDate = formatter.dateFromString(formatter.stringFromDate(endDate))
let sampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
let sampleQuery = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: {
(sampleQuery, results, error ) -> Void in
if let queryError = error {
print( "There was an error while reading the samples: \(queryError.localizedDescription)")
}
var steps: Double = 0
if results?.count > 0 {
for result in results as! [HKQuantitySample] {
steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
}
}
completion(Int(steps))
})
healthKitStore.executeQuery(sampleQuery)
}
func removeSample(sample: HKQuantitySample, completion: ( (Bool, NSError!) -> Void)!) {
self.healthKitStore.deleteObject(sample, withCompletion: { (results, error) -> Void in
completion(results, error)
})
}
}
|
apache-2.0
|
9a3b617aab99b0340b98de1fd3cce762
| 43.135417 | 155 | 0.641492 | 5.302879 | false | false | false | false |
voyages-sncf-technologies/Collor
|
Example/Collor/WeatherSample/WeatherCollectionData.swift
|
1
|
1897
|
//
// WeatherCollectionData.swift
// Collor
//
// Created by Guihal Gwenn on 26/07/2017.
// Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved.
//
import Foundation
import Collor
final class WeatherCollectionData : CollectionData {
var weatherModel:WeatherModel?
func reload(model:WeatherModel) {
weatherModel = model
reloadData()
}
override func reloadData() {
super.reloadData()
guard let weatherModel = self.weatherModel else {
return
}
let titleSection = WeatherSectionDescriptor(hasBackground: false).reloadSection { cells in
let header = TitleDescriptor(adapter: WeatherHeaderAdapter(cityName: weatherModel.cityName ))
cells.append(header)
}
sections.append(titleSection)
let daySections = weatherModel.weatherDays.map { day -> CollectionSectionDescribable in
let section = WeatherSectionDescriptor().uid(day.date.debugDescription)
section.reloadSection { cells in
let dayCellDescriptor = WeatherDayDescriptor(adapter: WeatherDayAdapter(day: day) ).uid("day")
cells.append( dayCellDescriptor )
if section.isExpanded {
let temperatureCellDescriptor = LabelDescriptor(adapter: WeatherTemperatureAdapter(day: day) ).uid("temp")
cells.append( temperatureCellDescriptor )
}
let pressureCellDescriptor = LabelDescriptor(adapter: WeatherPressureAdapter(day: day) ).uid("pressure")
cells.append( pressureCellDescriptor )
//}
}
return section
}
sections.append(contentsOf: daySections)
}
}
|
bsd-3-clause
|
3ebbe627a89183197de1fd7ad40a2256
| 33.490909 | 126 | 0.601476 | 5.313725 | false | false | false | false |
NghiaTranUIT/WatchKit-Apps
|
Carthage/Checkouts/Seru/Seru/Source/FetchResultControllerTableViewDataSource.swift
|
8
|
2769
|
//
// FetchResultControllerDataSource.swift
// Seru
//
// Created by Konstantin Koval on 08/09/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
import Foundation
import CoreData
import UIKit
public class FetchResultControllerTableViewDataSource : NSObject, UITableViewDataSource {
private var fetchedResultsController: NSFetchedResultsController
//public typealias cellConfigType = (UITableViewCell, NSManagedObject) -> ()
private var configureCell: (UITableViewCell, object: NSManagedObject) -> ()
public var editable: Bool
public init(fetchedResultsController: NSFetchedResultsController, editable: Bool = false, configureCell: (cell: UITableViewCell, object: NSManagedObject) -> ()) {
self.fetchedResultsController = fetchedResultsController
self.configureCell = configureCell
self.editable = editable
}
//MARK: - Public Interface
public func objectAtIndexPath(indexPath: NSIndexPath) -> NSManagedObject {
return fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
}
public subscript (indexPath: NSIndexPath) -> NSManagedObject {
return objectAtIndexPath(indexPath)
}
//MARK: - UITableViewDataSource
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionsInfo = self.fetchedResultsController.sectionsInfo
let sectionInfo = sectionsInfo[section]
return sectionInfo.numberOfObjects
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
configureCell(cell, object: self[indexPath])
return cell
}
// MARK: optionals
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let sectionsInfo = self.fetchedResultsController.sections as! [NSFetchedResultsSectionInfo]
return sectionsInfo.count
}
// MARK: Editable
public func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return editable
}
public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// let context = persistenceController.mainMOC
// context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject)
// persistenceController.persist()
}
}
}
extension NSFetchedResultsController {
var sectionsInfo: [NSFetchedResultsSectionInfo] {
return sections as! [NSFetchedResultsSectionInfo]
}
}
|
mit
|
5931802ac0f5681afbfccbcfccfe4b80
| 33.197531 | 164 | 0.767064 | 5.616633 | false | true | false | false |
shorlander/firefox-ios
|
Storage/Clients.swift
|
9
|
2580
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import SwiftyJSON
public struct RemoteClient: Equatable {
public let guid: GUID?
public let modified: Timestamp
public let name: String
public let type: String?
public let os: String?
public let version: String?
public let fxaDeviceId: String?
let protocols: [String]?
let appPackage: String?
let application: String?
let formfactor: String?
let device: String?
// Requires a valid ClientPayload (: CleartextPayloadJSON: JSON).
public init(json: JSON, modified: Timestamp) {
self.guid = json["id"].string
self.modified = modified
self.name = json["name"].stringValue
self.type = json["type"].string
self.version = json["version"].string
self.protocols = jsonsToStrings(json["protocols"].array)
self.os = json["os"].string
self.appPackage = json["appPackage"].string
self.application = json["application"].string
self.formfactor = json["formfactor"].string
self.device = json["device"].string
self.fxaDeviceId = json["fxaDeviceId"].string
}
public init(guid: GUID?, name: String, modified: Timestamp, type: String?, formfactor: String?, os: String?, version: String?, fxaDeviceId: String?) {
self.guid = guid
self.name = name
self.modified = modified
self.type = type
self.formfactor = formfactor
self.os = os
self.version = version
self.fxaDeviceId = fxaDeviceId
self.device = nil
self.appPackage = nil
self.application = nil
self.protocols = nil
}
}
// TODO: should this really compare tabs?
public func ==(lhs: RemoteClient, rhs: RemoteClient) -> Bool {
return lhs.guid == rhs.guid &&
lhs.name == rhs.name &&
lhs.modified == rhs.modified &&
lhs.type == rhs.type &&
lhs.formfactor == rhs.formfactor &&
lhs.os == rhs.os &&
lhs.version == rhs.version &&
lhs.fxaDeviceId == rhs.fxaDeviceId
}
extension RemoteClient: CustomStringConvertible {
public var description: String {
return "<RemoteClient GUID: \(guid ?? "nil"), name: \(name), modified: \(modified), type: \(type ?? "nil"), formfactor: \(formfactor ?? "nil"), OS: \(os ?? "nil"), version: \(version ?? "nil"), fxaDeviceId: \(fxaDeviceId ?? "nil")>"
}
}
|
mpl-2.0
|
48691f041df1aa283b24738279979d13
| 33.4 | 240 | 0.625969 | 4.350759 | false | false | false | false |
kmalkic/MKTween
|
MKTween/Group.swift
|
1
|
2823
|
//
// Group.swift
// MKTween
//
// Created by Kevin Malkic on 08/04/2019.
// Copyright © 2019 Kevin Malkic. All rights reserved.
//
import Foundation
public final class Group: BasePeriods {
public typealias UpdateBlock = (_ group: Group) -> ()
public typealias CompletionBlock = () -> ()
private(set) public var update: UpdateBlock?
private(set) public var completion: CompletionBlock?
private(set) public var name: String = UUID().uuidString
private(set) public var periodFinished: [Bool]
public let periods: [BasePeriod]
public let startTimestamp: TimeInterval
private(set) public var lastTimestamp: TimeInterval
public var delay: TimeInterval
public var duration: TimeInterval {
return periods.reduce(0) { (prev, period) -> TimeInterval in
max(prev, period.duration + period.delay)
} + delay
}
public var paused: Bool {
return periods.reduce(nil, { (prev, period) -> Bool in
if let prev = prev {
return prev && period.paused
}
return period.paused
}) ?? false
}
public init(periods: [BasePeriod], delay: TimeInterval = 0) {
self.delay = delay
self.periods = periods
let time = Date().timeIntervalSinceReferenceDate
self.startTimestamp = time
self.lastTimestamp = time
self.periodFinished = Array(repeating: false, count: periods.count)
}
public func updateInternal() -> Bool {
if delay <= 0 && !paused {
periods.enumerated().forEach { index, period in
if !periodFinished[index] && period.updateInternal() {
periodFinished[index] = true
}
}
return periodFinished.filter { !$0 }.isEmpty
} else if !paused {
let newTime = Date().timeIntervalSinceReferenceDate
let dt = lastTimestamp.deltaTime(from: newTime)
lastTimestamp = newTime
delay -= dt
}
return false
}
public func set(startTimestamp time: TimeInterval) {
periods.forEach { $0.set(startTimestamp: time) }
}
@discardableResult public func set(name: String) -> Self {
self.name = name
return self
}
public func callUpdateBlock() {
periods.forEach { $0.callUpdateBlock() }
update?(self)
}
public func callCompletionBlock() {
periods.forEach { $0.callCompletionBlock() }
completion?()
}
@discardableResult public func set(update: UpdateBlock? = nil, completion: CompletionBlock? = nil) -> Group {
self.update = update
self.completion = completion
return self
}
}
|
mit
|
dfe2d69fc65621cc358eefcced48330b
| 29.021277 | 113 | 0.587527 | 4.865517 | false | false | false | false |
corichmond/turbo-adventure
|
project12/Project10/ViewController.swift
|
20
|
4012
|
//
// ViewController.swift
// Project10
//
// Created by Hudzilla on 21/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var people = [Person]()
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "Names to Faces"
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addNewPerson")
let defaults = NSUserDefaults.standardUserDefaults()
if let savedPeople = defaults.objectForKey("people") as? NSData {
people = NSKeyedUnarchiver.unarchiveObjectWithData(savedPeople) as! [Person]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return people.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Person", forIndexPath: indexPath) as! PersonCell
let person = people[indexPath.item]
cell.name.text = person.name
let path = getDocumentsDirectory().stringByAppendingPathComponent(person.image)
cell.imageView.image = UIImage(contentsOfFile: path)
cell.imageView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor
cell.imageView.layer.borderWidth = 2
cell.imageView.layer.cornerRadius = 3
cell.layer.cornerRadius = 7
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let person = people[indexPath.item]
let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .Alert)
ac.addTextFieldWithConfigurationHandler(nil)
ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in
let newName = ac.textFields![0] as! UITextField
person.name = newName.text
self.collectionView.reloadData()
self.save()
})
presentViewController(ac, animated: true, completion: nil)
}
func addNewPerson() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var newImage: UIImage
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
newImage = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
newImage = possibleImage
} else {
return
}
let imageName = NSUUID().UUIDString
let imagePath = getDocumentsDirectory().stringByAppendingPathComponent(imageName)
let jpegData = UIImageJPEGRepresentation(newImage, 80)
jpegData.writeToFile(imagePath, atomically: true)
let person = Person(name: "", image: imageName)
people.append(person)
collectionView.reloadData()
dismissViewControllerAnimated(true, completion: nil)
save()
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func getDocumentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as! [String]
let documentsDirectory = paths[0]
return documentsDirectory
}
func save() {
let savedData = NSKeyedArchiver.archivedDataWithRootObject(people)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(savedData, forKey: "people")
}
}
|
unlicense
|
8149ba595abbf007dd8aacc4c34be387
| 30.84127 | 159 | 0.768694 | 4.559091 | false | false | false | false |
saagarjha/iina
|
iina/MPVFilter.swift
|
1
|
11125
|
//
// MPVFilter.swift
// iina
//
// Created by lhc on 2/9/16.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
// See https://github.com/mpv-player/mpv/blob/master/options/m_option.c#L3161
// #define NAMECH "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
fileprivate let mpvAllowedCharacters = Set<Character>("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
fileprivate extension String {
var mpvQuotedFilterValue: String {
return self.allSatisfy({ mpvAllowedCharacters.contains($0) }) ? self : mpvFixedLengthQuoted
}
}
/**
Represents a mpv filter. It can be either created by user or loaded from mpv.
*/
class MPVFilter: NSObject {
enum FilterType: String {
case crop = "crop"
case expand = "expand"
case flip = "flip"
case mirror = "hflip"
case lavfi = "lavfi"
}
// MARK: - Static filters
static func crop(w: Int?, h: Int?, x: Int?, y: Int?) -> MPVFilter {
let f = MPVFilter(name: "crop", label: nil,
params: ["w": w?.description ?? "", "h": h?.description ?? "", "x": x?.description ?? "", "y": y?.description ?? ""])
return f
}
// FIXME: use lavfi vflip
static func flip() -> MPVFilter {
return MPVFilter(name: "vflip", label: nil, params: nil)
}
// FIXME: use lavfi hflip
static func mirror() -> MPVFilter {
return MPVFilter(name: "hflip", label: nil, params: nil)
}
/**
A ffmpeg `unsharp` filter.
Args: l(uma)x, ly, la, c(hroma)x, xy, ca; default 5:5:0:5:5:0.
We only change la and ca here.
- parameter msize: Value for lx, ly, cx and cy. Should be an odd integer in [3, 23].
- parameter amount: Amount for la and ca. Should be in [-1.5, 1.5].
*/
static func unsharp(amount: Float, msize: Int = 5) -> MPVFilter {
let amoutStr = amount.description
let msizeStr = msize.description
return MPVFilter(lavfiName: "unsharp", label: nil, params: [msizeStr, msizeStr, amoutStr, msizeStr, msizeStr, amoutStr])
}
// MARK: - Members
var type: FilterType?
var name: String
var label: String?
var params: [String: String]?
var rawParamString: String?
/** Convert the filter to a valid mpv filter string. */
var stringFormat: String {
get {
var str = ""
// label
if let label = label { str += "@\(label):" }
// name
str += name
// params
if let rpstr = rawParamString {
// if is set by user
str += "="
str += rpstr
} else if params != nil && params!.count > 0 {
// if have format info, print using the format
if type != nil, let format = MPVFilter.formats[type!] {
str += "="
str += format.components(separatedBy: ":").map { params![$0] ?? "" }.joined(separator: ":")
// else print param names
} else {
str += "="
// special tweak for lavfi filters
if name == "lavfi" {
str += "[\(params!["graph"]!)]"
} else {
str += params!.map { "\($0)=\($1.mpvQuotedFilterValue)" } .joined(separator: ":")
}
}
}
return str
}
}
override var debugDescription: String {
Mirror(reflecting: self).children.map({"\($0.label!)=\($0.value)"}).joined(separator: ", ")
}
// MARK: - Initializers
init(name: String, label: String?, params: [String: String]?) {
self.type = FilterType(rawValue: name)
self.name = name
self.label = label
if let params = params, let type = type, let format = MPVFilter.formats[type]?.components(separatedBy: ":") {
var translated: [String: String] = [:]
for (key, value) in params {
if let number = Int(key.dropFirst()) {
translated[format[number]] = value
} else {
translated[key] = value
}
}
self.params = translated
} else {
self.params = params
}
}
init?(rawString: String) {
let splitted = rawString.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: true).map { String($0) }
guard splitted.count == 1 || splitted.count == 2 else { return nil }
self.name = splitted[0]
if name.hasPrefix("@") {
// The name starts with a label. Separate them into the respected properties.
name.removeFirst()
let nameSplitted = name.split(separator: ":", maxSplits: 1).map { String($0) }
guard nameSplitted.count == 2 else { return nil }
self.label = nameSplitted[0]
self.name = nameSplitted[1]
}
self.rawParamString = splitted[at: 1]
self.params = MPVFilter.parseRawParamString(name, rawParamString)
}
init(name: String, label: String?, paramString: String) {
self.name = name
self.type = FilterType(rawValue: name)
self.label = label
self.rawParamString = paramString
}
convenience init(lavfiName: String, label: String?, params: [String]) {
var ffmpegGraph = "[\(lavfiName)="
ffmpegGraph += params.joined(separator: ":")
ffmpegGraph += "]"
self.init(name: "lavfi", label: label, paramString: ffmpegGraph)
}
convenience init(lavfiName: String, label: String?, paramDict: [String: String]) {
var ffmpegGraph = "[\(lavfiName)="
ffmpegGraph += paramDict.map { "\($0)=\($1)" }.joined(separator: ":")
ffmpegGraph += "]"
self.init(name: "lavfi", label: label, paramString: ffmpegGraph)
}
convenience init(lavfiFilterFromPresetInstance instance: FilterPresetInstance) {
var dict: [String: String] = [:]
instance.params.forEach { (k, v) in
dict[k] = v.stringValue
}
self.init(lavfiName: instance.preset.name, label: nil, paramDict: dict)
}
convenience init(mpvFilterFromPresetInstance instance: FilterPresetInstance) {
var dict: [String: String] = [:]
instance.params.forEach { (k, v) in
dict[k] = v.stringValue
}
self.init(name: instance.preset.name, label: nil, params: dict)
}
// MARK: - Others
/** The parameter order when omitting their names. */
static let formats: [FilterType: String] = [
.crop: "w:h:x:y",
.expand: "w:h:x:y:aspect:round"
]
/// Names of filters without parameters or whose parameters do not need to be parsed.
private static let doNotParse = ["crop", "flip", "hflip", "lavfi"]
/// Parse the given string containing filter parameters.
///
/// Filters that support multiple parameters have more than one valid string representation due to there being no requirement on the
/// order in which those parameters are given in a filter. For such filters the string representation of the parameters needs to be parsed
/// to form a `Dictionary` containing individual parameter-value pairs. This allows the parameters of two `MPVFilter` objects
/// to be compared using a `Dictionary` to `Dictionary` comparison rather than a string comparison that might fail due to the
/// parameters being in a different order in the string. This method will return `nil` if it determines this kind of filter can be compared
/// using the string representation, or if parsing failed.
/// - Note:
/// Related issues:
/// * [Audio filters with same name cannot be removed. #3620](https://github.com/iina/iina/issues/3620)
/// * [mpv_get_property returns filter params in unordered map breaking remove #9841](https://github.com/mpv-player/mpv/issues/9841)
/// - Parameter name: Name of the filter.
/// - Parameter rawParamString: String to be parsed.
/// - Returns: A `Dictionary` containing the filter parameters or `nil` if the parameters were not parsed.
private static func parseRawParamString(_ name: String, _ rawParamString: String?) -> [String: String]? {
guard let rawParamString = rawParamString, !doNotParse.contains(name) else { return nil }
let pairs = rawParamString.split(separator: ":")
// If there is only one parameter then parameter order is not an issue.
guard pairs.count > 1 else { return nil }
var dict: [String: String] = [:]
for pair in pairs {
let split = pair.split(separator: "=", maxSplits: 1).map { String($0) }
guard split.count == 2 else {
// This indicates either this kind of filter needs to be added to the doNotParse list, or
// this parser needs to be enhanced to be able to parse the string representation of this
// kind of filter.
Logger.log("Unable to parse filter \(name) params: \(rawParamString)", level: .warning)
return nil
}
// Add the pair to the dictionary stripping any %n% style quoting from the front of the value.
dict[split[0]] = split[1].replacingOccurrences(of: "^%\\d+%", with: "",
options: .regularExpression)
}
return dict
}
// MARK: - Param getter
func cropParams(videoSize: NSSize) -> [String: Double] {
guard type == .crop else {
Logger.fatal("Trying to get crop params from a non-crop filter!")
}
guard let params = params else { return [:] }
// w and h should always valid
let w = Double(params["w"]!)!
let h = Double(params["h"]!)!
let x: Double, y: Double
// check x and y
if let testx = Double(params["x"] ?? ""), let testy = Double(params["y"] ?? "") {
x = testx
y = testy
} else {
let cx = Double(videoSize.width) / 2
let cy = Double(videoSize.height) / 2
x = cx - w / 2
y = cy - h / 2
}
return ["x": x, "y": y, "w": w, "h": h]
}
/// Returns `true` if this filter is equal to the given filter `false` otherwise.
///
/// Filters that support multiple parameters have more than one valid string representation due to there being no requirement on the
/// order in which those parameters are given in a filter. In the `mpv_node` tree returned for the mpv property representing the audio
/// filter list or the video filter list, filter parameters are contained in random order in a `MPV_FORMAT_NODE_MAP`. When IINA
/// converts the `mpv_node` tree into `MPVFilter` objects parameters are stored in a `Dictionary` which also does not
/// provide a predictable order. This is all correct behavior as per discussions with the mpv project in mpv issue #9841. Due to this
/// issue with the string representation of some types of filters this method gives preference to comparing the dictionaries in the
/// `params` property if available over comparing string representations.
/// - Note:
/// Related issues:
/// * [Audio filters with same name cannot be removed. #3620](https://github.com/iina/iina/issues/3620)
/// * [mpv_get_property returns filter params in unordered map breaking remove #9841](https://github.com/mpv-player/mpv/issues/9841)
/// - Parameter object: The object to compare to this filter.
/// - Returns: `true` if this filter is equal to the given object, otherwise `false`.
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MPVFilter, label == object.label, name == object.name else { return false }
if let lhs = params, let rhs = object.params {
return lhs == rhs
}
return stringFormat == object.stringFormat
}
}
|
gpl-3.0
|
a32e0f614a92b70bbc14d0e93c1d0a0a
| 38.870968 | 141 | 0.642754 | 4.024602 | false | false | false | false |
Adlai-Holler/ReactiveArray
|
ReactiveArray/Operation.swift
|
1
|
2948
|
//
// Operation.swift
// ReactiveArray
//
// Created by Guido Marucci Blas on 7/1/15.
// Copyright (c) 2015 Wolox. All rights reserved.
//
import Foundation
import Box
public enum Operation<T>: DebugPrintable {
case Append(value: Box<T>)
case Insert(value: Box<T>, atIndex: Int)
case RemoveElement(atIndex: Int)
public func map<U>(mapper: T -> U) -> Operation<U> {
let result: Operation<U>
switch self {
case .Append(let boxedValue):
result = Operation<U>.Append(value: Box(mapper(boxedValue.value)))
case .Insert(let boxedValue, let index):
result = Operation<U>.Insert(value: Box(mapper(boxedValue.value)), atIndex: index)
case .RemoveElement(let index):
result = Operation<U>.RemoveElement(atIndex: index)
}
return result
}
public var debugDescription: String {
let description: String
switch self {
case .Append(let boxedValue):
description = ".Append(value:\(boxedValue.value))"
case .Insert(let boxedValue, let index):
description = ".Insert(value: \(boxedValue.value), atIndex:\(index))"
case .RemoveElement(let index):
description = ".RemoveElement(atIndex:\(index))"
}
return description
}
public var value: T? {
switch self {
case .Append(let boxedValue):
return boxedValue.value
case .Insert(let boxedValue, let index):
return boxedValue.value
default:
return Optional.None
}
}
}
// TODO: Uses constrained protocol extension when moving to Swift 2.0
// extension Operation: Equatable where T: Equatable {}
public func ==<T: Equatable>(lhs: Operation<T>, rhs: Operation<T>) -> Bool {
switch (lhs, rhs) {
case (.Append(let leftBoxedValue), .Append(let rightBoxedValue)):
return leftBoxedValue.value == rightBoxedValue.value
case (.Insert(let leftBoxedValue, let leftIndex), .Insert(let rightBoxedValue, let rightIndex)):
return leftIndex == rightIndex && leftBoxedValue.value == rightBoxedValue.value
case (.RemoveElement(let leftIndex), .RemoveElement(let rightIndex)):
return leftIndex == rightIndex
default:
return false
}
}
// WTF!!! Again this is needed because the compiler is super stupid!
public func !=<T: Equatable>(lhs: Operation<T>, rhs: Operation<T>) -> Bool {
return !(lhs == rhs)
}
// This is needed because somehow the compiler does not realize
// that when T is equatable it can compare an array of operations.
public func ==<T: Equatable>(lhs: [Operation<T>], rhs: [Operation<T>]) -> Bool {
let areEqual: () -> Bool = {
for var i = 0; i < lhs.count; i++ {
if lhs[i] != rhs[i] {
return false
}
}
return true
}
return lhs.count == rhs.count && areEqual()
}
|
mit
|
da7b99009d15a67bc962cfda1424fb1e
| 31.766667 | 100 | 0.614654 | 4.247839 | false | false | false | false |
exyte/Macaw
|
Source/model/draw/Font.swift
|
1
|
275
|
open class Font {
public let name: String
public let size: Int
public let weight: String
public init(name: String = "Serif", size: Int = 12, weight: String = "normal") {
self.name = name
self.size = size
self.weight = weight
}
}
|
mit
|
474741855c9456b45a3521a28fe47267
| 21.916667 | 84 | 0.585455 | 3.928571 | false | false | false | false |
beyerss/CalendarKit
|
CalendarKitTests/CalendarConfigurationTests.swift
|
1
|
8513
|
//
// CalendarConfigurationTests.swift
// CalendarKit
//
// Created by Steven Beyers on 6/17/16.
// Copyright © 2016 Beyers Apps, LLC. All rights reserved.
//
import XCTest
@testable import CalendarKit
class CalendarConfigurationTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCustomDateCellConfiguration() {
let textStyle = ViewPlacement.TopCenter(verticalOffset: 8)
let weekdayHeaderColor = UIColor(red: 157/255, green: 56/255, blue: 155/255, alpha: 1.0)
let circleSizeOffset: CGFloat = -7
let font = UIFont(name: "AmericanTypewriter-Bold", size: 10)!
let backgroundColor = UIColor.whiteColor()
let disabledBackgroundColor = UIColor.darkGrayColor()
let highlightColor = UIColor(red: 158/255, green: 56/255, blue: 155/255, alpha: 1.0)
let textEnabledColor = UIColor(red: 158/255, green: 56/255, blue: 1/255, alpha: 1.0)
let textDisabledColor = UIColor.lightGrayColor()
let textHighlightColor = weekdayHeaderColor.colorWithAlphaComponent(0.6)
let textSelectedColor = UIColor.whiteColor()
let heightForDynamicHeightRows: CGFloat = 40.0
let dateCellConfiguration = DateCellConfiguration(textStyle: textStyle, circleSizeOffset: circleSizeOffset, font: font, backgroundColor: backgroundColor, disabledBackgroundColor: disabledBackgroundColor, highlightColor: highlightColor, textEnabledColor: textEnabledColor, textDisabledColor: textDisabledColor, textHighlightedColor: textHighlightColor, textSelectedColor: textSelectedColor, heightForDynamicHeightRows: heightForDynamicHeightRows)
switch textStyle {
case .TopCenter(verticalOffset: let offset):
switch dateCellConfiguration.textStyle {
case .TopCenter(verticalOffset: let configOffset):
XCTAssertTrue(offset == configOffset, "Text style was not set properly")
default:
XCTFail("Text style was not set properly")
}
default:
XCTFail("Text style was not set properly")
}
XCTAssertTrue(circleSizeOffset == dateCellConfiguration.circleSizeOffset, "CircleSizeOffset was not set properly")
XCTAssertTrue(font == dateCellConfiguration.font, "Font was not set properly")
XCTAssertTrue(backgroundColor == dateCellConfiguration.backgroundColor, "BackgroundColor was not set properly")
XCTAssertTrue(disabledBackgroundColor == dateCellConfiguration.disabledBackgroundColor, "DisabledBackgroundColor was not set properly")
XCTAssertTrue(highlightColor == dateCellConfiguration.highlightColor, "HighlightColor was not set properly")
XCTAssertTrue(textEnabledColor == dateCellConfiguration.textEnabledColor, "TextEnabledColor was not set properly")
XCTAssertTrue(textDisabledColor == dateCellConfiguration.textDisabledColor, "TextDisabledColor was not set properly")
XCTAssertTrue(textHighlightColor == dateCellConfiguration.textHighlightedColor, "TextHighlightColor was not set properly")
XCTAssertTrue(textSelectedColor == dateCellConfiguration.textSelectedColor, "TextSelectedColor was not set properly")
XCTAssertTrue(heightForDynamicHeightRows == dateCellConfiguration.heightForDynamicHeightRows, "HeightForDynamicHeightRows was not set properly")
}
func testCustomHeaderConfiguration() {
let font = UIFont(name: "AmericanTypewriter", size: 13)!
let textColor = UIColor.lightGrayColor()
let backgroundColor = UIColor.redColor()
let height: CGFloat = 20
let headerConfig = HeaderConfiguration(font: font, textColor: textColor, backgroundColor: backgroundColor, height: height)
XCTAssertTrue(font == headerConfig.font, "Font was not set properly")
XCTAssertTrue(textColor == headerConfig.textColor, "TextColor was not set properly")
XCTAssertTrue(backgroundColor == headerConfig.backgroundColor, "BackgroundColor was not set properly")
XCTAssertTrue(height == headerConfig.height, "Height was not set properly")
}
func testCustomCalendarLogicConfiguration() {
let minDate = NSDate()
let maxDate = NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 31)
let disabledDates: [NSDate] = [NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 2), NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 7), NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 8)]
let disableWeekends = true
let logicConfig = CalendarLogicConfiguration(minDate: minDate, maxDate: maxDate, disabledDates: disabledDates, disableWeekends: disableWeekends)
XCTAssertTrue(minDate == logicConfig.minDate, "MinDate was not set properly")
XCTAssertTrue(maxDate == logicConfig.maxDate, "MaxDate was not set properly")
XCTAssertTrue(disabledDates == logicConfig.disabledDates!, "DisabledDates was not set properly")
XCTAssertTrue(disableWeekends == logicConfig.shouldDisableWeekends, "ShouldDisableWeekends was not set properly")
}
func testFullScreenConfigurationHelper() {
let fullScreenConfig = CalendarConfiguration.FullScreenConfiguration()
XCTAssertTrue(fullScreenConfig.displayStyle == .FullScreen, "FullScreen display style not set")
}
func testInputViewConfigurationHelper() {
let inputConfig = CalendarConfiguration.InputViewConfiguration()
XCTAssertTrue(inputConfig.displayStyle == .InputView, "Input display style not set")
}
func testCustomConfiguration() {
// Basic setup stuff
let weekdayHeaderColor = UIColor(red: 157/255, green: 56/255, blue: 155/255, alpha: 1.0)
let dateCellConfiguration = DateCellConfiguration(textStyle: .TopCenter(verticalOffset: 8), circleSizeOffset: -7, font: UIFont(name: "AmericanTypewriter-Bold", size: 10)!, backgroundColor: UIColor.whiteColor(), disabledBackgroundColor: UIColor.darkGrayColor(), highlightColor: weekdayHeaderColor, textEnabledColor: weekdayHeaderColor, textDisabledColor: UIColor.lightGrayColor(), textHighlightedColor: weekdayHeaderColor.colorWithAlphaComponent(0.6), textSelectedColor: UIColor.whiteColor(), heightForDynamicHeightRows: 40.0)
let monthHeaderConfig = HeaderConfiguration(font: UIFont(name: "AmericanTypewriter-Bold", size: 30)!, textColor: UIColor.lightGrayColor(), backgroundColor: UIColor.purpleColor(), height: 40.0)
let weekdayHeaderConfig = HeaderConfiguration(font: UIFont(name: "AmericanTypewriter", size: 13)!, textColor: UIColor.lightGrayColor(), backgroundColor: weekdayHeaderColor, height: 20.0)
let disabledDates: [NSDate] = [NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 2), NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 7), NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 8)]
let logicConfig = CalendarLogicConfiguration(minDate: NSDate(), maxDate: NSDate().dateByAddingTimeInterval(60 * 60 * 24 * 31), disabledDates: disabledDates, disableWeekends: false)
// Testable configuration values
let displayStyle = DisplayStyle.Custom
let monthFormat = "MMMM yyyy"
let backgroundColor = UIColor.greenColor()
let hasDynamicHeight = true
let space: CGFloat = 4.0
let config = CalendarConfiguration(displayStyle: displayStyle, monthFormat: monthFormat, calendarBackgroundColor: backgroundColor, hasDynamicHeight: hasDynamicHeight, spaceBetweenDates: space, monthHeaderConfiguration: monthHeaderConfig, weekdayHeaderConfiguration: weekdayHeaderConfig, dateCellConfiguration: dateCellConfiguration, logicConfiguration: logicConfig)
XCTAssertTrue(displayStyle == config.displayStyle, "DisplayStyle not set properly")
XCTAssertTrue(monthFormat == config.monthFormat, "MonthFormat not set properly")
XCTAssertTrue(backgroundColor == config.backgroundColor, "BackgroundColor not set properly")
XCTAssertTrue(hasDynamicHeight == config.dynamicHeight, "DynamicHeight not set properly")
XCTAssertTrue(space == config.spaceBetweenDates, "SpaceBetweenDates not set properly")
}
}
|
mit
|
d1c29e58d979277d2031068344c93d7d
| 64.984496 | 533 | 0.729793 | 5.380531 | false | true | false | false |
larryhou/swift
|
TexasHoldem/TexasHoldem/HandV5Straight.swift
|
1
|
947
|
//
// HandV5Straight.swift
// TexasHoldem
//
// Created by larryhou on 6/3/2016.
// Copyright © 2016 larryhou. All rights reserved.
//
import Foundation
// 顺子
class HandV5Straight: PatternEvaluator {
static func getOccurrences() -> UInt {
return
10 * pow(4, exponent: 5) *
combinate(52 - 5, select: 2)
}
static func evaluate(_ hand: PokerHand) {
var cards = (hand.givenCards + hand.tableCards).sort()
if cards[0].value == 1 {
cards.append(cards[0])
}
var stack = [cards[0]]
for i in 0..<cards.count - 1 {
if (cards[i].value - cards[i + 1].value == 1) || (cards[i].value == 1/*A*/ && cards[i + 1].value == 13/*K*/) {
stack.append(cards[i + 1])
} else
if stack.count < 5 {
stack = [cards[i + 1]]
}
}
hand.matches = Array(stack[0..<5])
}
}
|
mit
|
a2fceeeff7694d76c47caa8828e02985
| 24.459459 | 122 | 0.501062 | 3.425455 | false | false | false | false |
sovereignshare/fly-smuthe
|
Fly Smuthe/Fly Smuthe/DateUtility.swift
|
1
|
4028
|
//
// DateUtility.swift
// Fly Smuthe
//
// Created by Adam M Rivera on 3/22/15.
// Copyright (c) 2015 Adam M Rivera. All rights reserved.
//
import Foundation
class DateUtility {
class func toUTCDate(dateString: String) -> NSDate {
let dateFormatter = NSDateFormatter();
let timeZone = NSTimeZone(name: "CDT");
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
dateFormatter.timeZone = timeZone;
let date = dateFormatter.dateFromString(dateString);
return date!;
}
class func toLocalDateString(date: NSDate!) -> String {
if(date == nil){
return "";
}
let dateFormatter = NSDateFormatter();
let timeZone = NSTimeZone.defaultTimeZone();
dateFormatter.timeZone = timeZone;
dateFormatter.dateFormat = "MMM d, h:mma";
return dateFormatter.stringFromDate(date);
}
class func toServerDateString(date: NSDate!) -> String {
if(date == nil){
return "";
}
let dateFormatter = NSDateFormatter();
let timeZone = NSTimeZone(name: "CDT");
dateFormatter.timeZone = timeZone;
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
return dateFormatter.stringFromDate(date);
}
}
extension NSDate: Comparable {
}
func + (date: NSDate, timeInterval: NSTimeInterval) -> NSDate {
return date.dateByAddingTimeInterval(timeInterval)
}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
if lhs.compare(rhs) == .OrderedSame {
return true
}
return false
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
if lhs.compare(rhs) == .OrderedAscending {
return true
}
return false
}
extension NSTimeInterval {
var withMinutes: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
return self * secondsInAMinute;
}
var second: NSTimeInterval {
return self.seconds
}
var seconds: NSTimeInterval {
return self
}
var minute: NSTimeInterval {
return self.minutes
}
var minutes: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
return self / secondsInAMinute
}
var hours: NSTimeInterval {
let secondsInAMinute = 60 as NSTimeInterval
let minutesInAnHour = 60 as NSTimeInterval
return self / secondsInAMinute / minutesInAnHour
}
var day: NSTimeInterval {
return self.days
}
var days: NSTimeInterval {
let secondsInADay = 86_400 as NSTimeInterval
return self / secondsInADay
}
var fromNowFriendlyString: String {
var returnStr = "";
if(self > 0){
if(self.days >= 1){
returnStr = String(Int(floor(self.days))) + " day";
} else if (self.hours >= 1){
let hours = Int(floor(self.hours));
returnStr = String(hours) + " hour" + (hours > 1 ? "s" : "");
} else if (self.minutes >= 1){
let minutes = Int(floor(self.minutes));
returnStr = String(minutes) + " minute" + (minutes > 1 ? "s" : "");
} else if (self >= 1){
let seconds = Int(self);
returnStr = String(seconds) + " second" + (seconds > 1 ? "s" : "");
}
}
return returnStr;
}
var timerString: String {
let interval = Int(self);
let seconds = interval % 60;
let minutes = (interval / 60) % 60;
return String(format: "%02d:%02d", minutes, seconds)
}
var fromNow: NSDate {
let timeInterval = self
return NSDate().dateByAddingTimeInterval(timeInterval)
}
func from(date: NSDate) -> NSDate {
let timeInterval = self
return date.dateByAddingTimeInterval(timeInterval)
}
var ago: NSDate {
let timeInterval = self
return NSDate().dateByAddingTimeInterval(-timeInterval)
}
}
|
gpl-3.0
|
4bf5b1e7fd199cc358ca1abb36224823
| 26.786207 | 83 | 0.578699 | 4.640553 | false | false | false | false |
remlostime/one
|
one/one/ViewControllers/FollowViewController.swift
|
1
|
6064
|
//
// FollowViewController.swift
// one
//
// Created by Kai Chen on 2/13/17.
// Copyright © 2017 Kai Chen. All rights reserved.
//
import UIKit
import Parse
enum FollowViewStatus: String {
case Followers
case Following
}
class FollowViewController: UITableViewController {
var followers = [String]()
var followings = [String]()
var profileImages = [PFFile]()
var usernames = [String]()
var status: FollowViewStatus = .Followers
let currentUserID = PFUser.current()?.username
override func viewDidLoad() {
super.viewDidLoad()
self.title = status.rawValue
switch status {
case .Followers:
loadFollowers()
case .Following:
loadFollowing()
}
}
func loadFollowing() {
guard let currentUserID = currentUserID else {
return
}
let followingQuery = PFQuery(className: Follow.modelName.rawValue)
followingQuery.whereKey(Follow.follower.rawValue, equalTo: currentUserID)
followingQuery.findObjectsInBackground { [weak self](objects: [PFObject]?, error: Error?) in
if error == nil {
guard let strongSelf = self else {
return
}
strongSelf.followings.removeAll()
for object in objects! {
strongSelf.followings.append(object.value(forKey: Follow.following.rawValue) as! String)
}
let query = PFUser.query()
query?.whereKey(User.id.rawValue, containedIn: strongSelf.followings)
query?.addDescendingOrder(Info.createTime.rawValue)
query?.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if error == nil {
strongSelf.usernames.removeAll()
strongSelf.profileImages.removeAll()
for object in objects! {
strongSelf.usernames.append(object.object(forKey: User.id.rawValue) as! String)
strongSelf.profileImages.append(object.object(forKey: User.profileImage.rawValue) as! PFFile)
}
strongSelf.tableView.reloadData()
} else {
print("error:\(error!.localizedDescription)")
}
})
}
}
}
func loadFollowers() {
guard let currentUserID = currentUserID else {
return
}
let followingQuery = PFQuery(className: Follow.modelName.rawValue)
followingQuery.whereKey(Follow.follower.rawValue, equalTo: currentUserID)
followingQuery.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if error == nil {
self.followings.removeAll()
for object in objects! {
self.followings.append(object.value(forKey: Follow.following.rawValue) as! String)
}
}
}
let followQuery = PFQuery(className: Follow.modelName.rawValue)
followQuery.whereKey(Follow.following.rawValue, equalTo: currentUserID)
followQuery.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
if error == nil {
self.followers.removeAll()
for object in objects! {
self.followers.append(object.value(forKey: Follow.follower.rawValue) as! String)
}
let query = PFUser.query()
query?.whereKey(User.id.rawValue, containedIn: self.followers)
query?.addDescendingOrder(Info.createTime.rawValue)
query?.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if error == nil {
self.usernames.removeAll()
self.profileImages.removeAll()
for object in objects! {
self.usernames.append(object.object(forKey: User.id.rawValue) as! String)
self.profileImages.append(object.object(forKey: User.profileImage.rawValue) as! PFFile)
}
self.tableView.reloadData()
} else {
print("error:\(error!.localizedDescription)")
}
})
} else {
print("error:\(error!.localizedDescription)")
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return usernames.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.followViewCell.rawValue, for: indexPath) as? FollowViewCell
cell?.tag = indexPath.row
let username = usernames[indexPath.row]
cell?.usernameLabel?.text = username
if followings.contains(username) {
cell?.configure(withState: .following)
} else {
cell?.configure(withState: .notFollowing)
}
let pfFile = profileImages[indexPath.row]
pfFile.getDataInBackground { (data: Data?, error: Error?) in
let image = UIImage(data: data!)
cell?.profielImageView?.image = image
}
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as? FollowViewCell
let username = cell?.usernameLabel.text
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: Identifier.profileViewController.rawValue) as? ProfileViewController
homeVC?.userid = username
self.navigationController?.pushViewController(homeVC!, animated: true)
}
}
|
gpl-3.0
|
e0940865510e8023be004c38b5763eb2
| 34.87574 | 148 | 0.579581 | 5.337148 | false | false | false | false |
fireflyexperience/Eki
|
Eki/Task.swift
|
1
|
1845
|
//
// Task.swift
// Eki
//
// Created by Jeremy Marchand on 20/10/2014.
// Copyright (c) 2014 Jérémy Marchand. All rights reserved.
//
import Foundation
/**
Chainable type
*/
public protocol Chainable {
func chain(block:() -> Void) -> Chainable
func chain(task:Task) -> Chainable
}
/**
A task is defined by a queue and a block
*/
public class Task:Chainable {
public let queue:Queue
internal let dispatchBlock:dispatch_block_t
public var block:() -> Void { return dispatchBlock }
public init(queue:Queue = Queue.Background, block:() -> Void) {
self.queue = queue
self.dispatchBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block)
}
private init(queue:Queue = Queue.Background, dispatchBlock:dispatch_block_t) {
self.queue = queue
self.dispatchBlock = dispatchBlock
}
//MARK: - Dispatch
public func async() -> Chainable {
queue.async(dispatchBlock)
return self
}
public func sync() -> Chainable{
queue.sync(dispatchBlock)
return self
}
public func cancel() {
dispatch_block_cancel(dispatchBlock)
}
//MARK: - Chain
public func chain(task:Task) -> Chainable {
dispatch_block_notify(self.dispatchBlock, task.queue.dispatchQueue, task.dispatchBlock)
return task
}
public func chain(block:() -> Void) -> Chainable {
let task = Task(queue: queue, block: block)
return chain(task)
}
}
//MARK: Operator
infix operator <> {associativity left precedence 110}
public func <> (c:Chainable, block:() -> Void) -> Chainable {
return c.chain(block)
}
public func <> (c:Chainable, task:Task) -> Chainable {
return c.chain(task)
}
public func + (q:Queue, block:() -> Void) -> Task {
return Task(queue: q, block: block)
}
|
mit
|
11205c845e43939948b4cd7ff55e4557
| 24.957746 | 95 | 0.636462 | 3.792181 | false | false | false | false |
quadro5/swift3_L
|
swift_question.playground/Pages/Let7 Reverse Integer .xcplaygroundpage/Contents.swift
|
1
|
806
|
//: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
// getting Int limit
// Int may vary based on the system
// On 32-bit platforms, Int is the same size as Int32,
// On 64-bit platforms, Int is the same size as Int64.
// lets assume 64-bit platforms
class Solution {
func reverse(_ x: Int) -> Int {
var isPositive = true
if x < 0 {
isPositive = false
}
var num = abs(x)
var digit: Int = 0
var res: Int = 0
while num > 0 {
digit = num % 10
num /= 10
res = res * 10 + digit
}
if res > Int(Int32.max) {
return 0
}
if isPositive == false {
return -res
}
return res
}
}
|
unlicense
|
8800e0f273b52c88f136a0e74b7ed564
| 19.175 | 54 | 0.493797 | 3.970443 | false | false | false | false |
hhyyg/Miso.Gistan
|
GistanFileExtension/FileProviderService.swift
|
1
|
2494
|
//
// FileProviderService.swift
// GistanFileExtension
//
// Created by Hiroka Yago on 2017/10/14.
// Copyright © 2017 miso. All rights reserved.
//
import FileProvider
class FileProviderSerivce {
static func getChildlenEnumerator(identifier: NSFileProviderItemIdentifier) -> NSFileProviderEnumerator {
let gistItem = getGistItem(identifier: identifier)
return GistItemFileProviderEnumerator(parentItem: gistItem, parentItemIdentifier: identifier)
}
//GistItemのIdentifierからGistItemを返す(TODO:identifierがItem限定)
static func getGistItem(identifier: NSFileProviderItemIdentifier) -> GistItem {
let identifierComponents = identifier.rawValue.components(separatedBy: ".")
let gistId = identifierComponents.last!
let foundItem = GistService.gistItems.filter { return $0.id == gistId }.first!
return foundItem
}
//identifierから、その親のIdentifierを取得する
static func getParentIdentifier(identifier: NSFileProviderItemIdentifier) ->
NSFileProviderItemIdentifier {
let identifierRaw = identifier.rawValue
var components = identifierRaw.components(separatedBy: ".")
assert(components.count == 4)
components.removeLast()
let parentIdentifierRaw = components.joined(separator: ".")
return NSFileProviderItemIdentifier(parentIdentifierRaw)
}
static func getGileFile(gistFileIdentifier: NSFileProviderItemIdentifier) -> GistFile? {
let parentIdentifier = FileProviderSerivce.getParentIdentifier(identifier: gistFileIdentifier)
let parentGistItem = FileProviderSerivce.getGistItem(identifier: parentIdentifier)
let fileNameEncoded = gistFileIdentifier.rawValue.components(separatedBy: ".").last!.urlDecoding()
let gistFile = parentGistItem.files.filter { key, _ in
return key == fileNameEncoded
}.first?.value
return gistFile
}
//identifiierから、それがGistItemかGistFileかを返す
static func getIdentifierType(identifier: NSFileProviderItemIdentifier) -> IdentifierType {
if identifier == NSFileProviderItemIdentifier.rootContainer {
return .root
}
switch identifier.rawValue.components(separatedBy: ".").count {
case 3:
return .gistItem
case 4:
return .gistFile
default:
fatalError("invalid")
}
}
}
|
mit
|
7ae6947b53d004fed48c4b63de22428f
| 37.492063 | 109 | 0.699794 | 4.969262 | false | false | false | false |
CaiMiao/CGSSGuide
|
DereGuide/Toolbox/Colleague/Controller/ColleagueViewController.swift
|
1
|
7663
|
//
// ColleagueViewController.swift
// DereGuide
//
// Created by zzk on 2017/8/2.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import CloudKit
import CoreData
import EasyTipView
import ZKDrawerController
class ColleagueViewController: BaseTableViewController {
lazy var filterController: ColleagueFilterController = {
let vc = ColleagueFilterController(style: .grouped)
vc.delegate = self
return vc
}()
private var refresher = CGSSRefreshHeader()
private var loader = CGSSRefreshFooter()
override func viewDidLoad() {
super.viewDidLoad()
prepareNavigationBar()
tableView.register(ColleagueTableViewCell.self, forCellReuseIdentifier: ColleagueTableViewCell.description())
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 159
tableView.tableFooterView = UIView()
tableView.backgroundColor = .white
tableView.separatorStyle = .none
tableView.mj_header = refresher
refresher.refreshingBlock = { [weak self] in
self?.fetchLatestProfiles()
}
tableView.mj_footer = loader
loader.refreshingBlock = { [weak self] in
self?.fetchMore {
self?.loader.state = self?.cursor == nil ? .noMoreData : .idle
}
}
refresher.beginRefreshing()
}
var remote = ProfileRemote()
var cursor: CKQueryCursor?
var profiles = [Profile]()
lazy var currentSetting: ColleagueFilterController.FilterSetting = self.filterController.setting
private var isFetching: Bool = false
@objc func fetchLatestProfiles() {
isFetching = true
remote.fetchRecordsWith([currentSetting.predicate], [remote.defaultSortDescriptor], resultsLimit: Config.cloudKitFetchLimits) { (remoteProfiles, cursor, error) in
DispatchQueue.main.async {
if error != nil {
UIAlertController.showHintMessage(NSLocalizedString("获取数据失败,请检查您的网络并确保iCloud处于登录状态", comment: ""), in: nil)
} else {
self.profiles = remoteProfiles.map { Profile.insert(remoteRecord: $0, into: self.childContext) }
}
self.isFetching = false
self.refresher.endRefreshing()
self.cursor = cursor
self.loader.state = cursor == nil ? .noMoreData : .idle
self.tableView.reloadData()
}
}
}
func fetchMore(completion: @escaping () -> ()) {
guard let cursor = cursor else {
completion()
return
}
isFetching = true
remote.fetchRecordsWith(cursor: cursor, resultsLimit: Config.cloudKitFetchLimits) { (remoteProfiles, cursor, error) in
DispatchQueue.main.async {
self.isFetching = false
if error != nil {
UIAlertController.showHintMessage(NSLocalizedString("获取数据失败,请检查您的网络并确保iCloud处于登录状态", comment: ""), in: nil)
} else {
let moreProfiles = remoteProfiles.map { Profile.insert(remoteRecord: $0, into: self.childContext) }
self.profiles.append(contentsOf: moreProfiles)
self.cursor = cursor
self.tableView.beginUpdates()
self.tableView.insertRows(at: moreProfiles.enumerated().map { IndexPath.init(row: $0.offset + self.profiles.count - moreProfiles.count, section: 0) }, with: .automatic)
self.tableView.endUpdates()
}
completion()
}
}
self.cursor = nil
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ColleagueTableViewCell.description(), for: indexPath) as! ColleagueTableViewCell
cell.setup(profiles[indexPath.row])
cell.delegate = self
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profiles.count
}
var context: NSManagedObjectContext {
return CoreDataStack.default.viewContext
}
lazy var profile: Profile = Profile.findOrCreate(in: self.context, configure: { _ in })
lazy var childContext: NSManagedObjectContext = self.context.newChildContext()
private var item: UIBarButtonItem!
private func prepareNavigationBar() {
let compose = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(composeAction))
let filter = UIBarButtonItem(image: #imageLiteral(resourceName: "798-filter-toolbar"), style: .plain, target: self, action: #selector(filterAction))
navigationItem.rightBarButtonItems = [compose, filter]
navigationItem.title = NSLocalizedString("寻找同僚", comment: "")
}
@objc func composeAction() {
// let vc = ColleagueComposeViewController()
// vc.setup(parentProfile: profile)
// vc.delegate = self
let vc = DMComposingStepOneController()
if UIDevice.current.userInterfaceIdiom == .pad {
let nav = BaseNavigationController(rootViewController: vc)
let drawer = ZKDrawerController(main: nav)
drawer.modalPresentationStyle = .formSheet
present(drawer, animated: true, completion: nil)
} else {
navigationController?.pushViewController(vc, animated: true)
}
}
@objc func filterAction() {
let nav = BaseNavigationController(rootViewController: filterController)
let drawer = ZKDrawerController(main: nav)
drawer.modalPresentationStyle = .formSheet
present(drawer, animated: true, completion: nil)
}
}
extension ColleagueViewController: ColleagueTableViewCellDelegate {
func colleagueTableViewCell(_ cell: ColleagueTableViewCell, didTap cardIcon: CGSSCardIconView) {
if let cardID = cardIcon.cardID, let card = CGSSDAO.shared.findCardById(cardID) {
let vc = CardDetailViewController()
vc.card = card
navigationController?.pushViewController(vc, animated: true)
}
}
@nonobjc func colleagueTableViewCell(_ cell: ColleagueTableViewCell, didTap gameID: String) {
UIPasteboard.general.string = gameID
UIAlertController.showHintMessage(NSLocalizedString("已复制ID到剪贴板", comment: ""), in: nil)
}
}
extension ColleagueViewController: ColleagueComposeViewControllerDelegate {
func didSave(_ colleagueComposeViewController: ColleagueComposeViewController) {
}
func didPost(_ colleagueComposeViewController: ColleagueComposeViewController) {
refresher.beginRefreshing()
// fetchLatestProfiles()
}
func didRevoke(_ colleagueComposeViewController: ColleagueComposeViewController) {
refresher.beginRefreshing()
// fetchLatestProfiles()
}
}
extension ColleagueViewController: ColleagueFilterControllerDelegate {
func didDone(_ colleagueFilterController: ColleagueFilterController) {
currentSetting = filterController.setting
refresher.beginRefreshing()
// fetchLatestProfiles()
}
}
|
mit
|
7a0cb3d3f58bc863dacef96911a75028
| 36.172414 | 188 | 0.645773 | 5.317829 | false | false | false | false |
rusty1s/RSContactGrid
|
RSContactGrid/RSContactGrid/Implementation/Grid.swift
|
1
|
2024
|
//
// Grid.swift
// RSContactGrid
//
// Created by Matthias Fey on 24.06.15.
// Copyright © 2015 Matthias Fey. All rights reserved.
//
public struct Grid<T : TileType> : GridType {
// MARK: Associated types
public typealias ElementType = T
// MARK: Instance variables
private var elements: Set<ElementType>
}
// MARK: Initializers
extension Grid {
public init() {
elements = Set()
}
public init(minimumCapacity: Int) {
elements = Set(minimumCapacity: minimumCapacity)
}
public init<S : SequenceType where S.Generator.Element == ElementType>(_ sequence: S) {
elements = Set(sequence)
}
}
// MARK: Instance variables
extension Grid {
public var count: Int { return elements.count }
}
// MARK: Instance methods
extension Grid {
public mutating func insert(element: ElementType) { elements.insert(element) }
public mutating func remove(element: ElementType) -> ElementType? { return elements.remove(element) }
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
elements.removeAll(keepCapacity: keepCapacity)
}
}
// MARK: Subscripts
extension Grid {
public subscript(x: Int, y: Int) -> ElementType? {
let element = ElementType(x: x, y: y)
guard let index = elements.indexOf(element) else { return nil }
return elements[index]
}
}
// MARK: Hashable
extension Grid {
public var hashValue: Int { return elements.hashValue }
}
// MARK: Equatable
extension Grid {}
public func == <T: TileType>(lhs: Grid<T>, rhs: Grid<T>) -> Bool {
return lhs.elements == rhs.elements
}
// MARK: SequenceType
extension Grid {
public typealias Generator = SetGenerator<ElementType>
public func generate() -> Generator {
return elements.generate()
}
}
// MARK: CustomDebugStringConvertible
extension Grid {
public var debugDescription: String { return "Grid(\(self)" }
}
|
mit
|
912754421abe9e33dad2eb99fde7c7d3
| 19.434343 | 105 | 0.643599 | 4.25 | false | false | false | false |
bkmunar/firefox-ios
|
UITests/Global.swift
|
1
|
5557
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
extension XCTestCase {
func tester(_ file: String = __FILE__, _ line: Int = __LINE__) -> KIFUITestActor {
return KIFUITestActor(inFile: file, atLine: line, delegate: self)
}
func system(_ file: String = __FILE__, _ line: Int = __LINE__) -> KIFSystemTestActor {
return KIFSystemTestActor(inFile: file, atLine: line, delegate: self)
}
}
extension KIFUITestActor {
/**
* Finding views by accessibility label doesn't currently work with WKWebView:
* https://github.com/kif-framework/KIF/issues/460
* As a workaround, inject a KIFHelper class that iterates the document and finds
* elements with the given textContent or title.
*/
func waitForWebViewElementWithAccessibilityLabel(text: String) {
let webView = waitForViewWithAccessibilityLabel("Web content") as! WKWebView
// Wait for the webView to stop loading.
runBlock({ _ in
return webView.loading ? KIFTestStepResult.Wait : KIFTestStepResult.Success
})
lazilyInjectKIFHelper(webView)
var stepResult = KIFTestStepResult.Wait
let escaped = text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
webView.evaluateJavaScript("KIFHelper.selectElementWithAccessibilityLabel(\"\(escaped)\");", completionHandler: { (result: AnyObject!, error: NSError!) in
stepResult = result as! Bool ? KIFTestStepResult.Success : KIFTestStepResult.Failure
})
runBlock({ (error: NSErrorPointer) in
if stepResult == KIFTestStepResult.Failure {
error.memory = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Accessibility label not found in webview: \(escaped)"])
}
return stepResult
})
}
private func lazilyInjectKIFHelper(webView: WKWebView) {
var stepResult = KIFTestStepResult.Wait
webView.evaluateJavaScript("typeof KIFHelper;", completionHandler: { (result: AnyObject!, error: NSError!) in
if result as! String == "undefined" {
let bundle = NSBundle(forClass: NavigationTests.self)
let path = bundle.pathForResource("KIFHelper", ofType: "js")!
let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)!
webView.evaluateJavaScript(source as String, completionHandler: nil)
}
stepResult = KIFTestStepResult.Success
})
runBlock({ _ in
return stepResult
})
}
// TODO: Click element, etc.
}
class BrowserUtils {
/// Close all tabs to restore the browser to startup state.
class func resetToAboutHome(tester: KIFUITestActor) {
tester.tapViewWithAccessibilityLabel("Show Tabs")
let tabsView = tester.waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView
while tabsView.numberOfItemsInSection(0) > 1 {
let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))!
tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left)
tester.waitForAbsenceOfViewWithAccessibilityLabel(cell.accessibilityLabel)
}
// When the last tab is closed, the tabs tray will automatically be closed
// since a new about:home tab will be selected.
let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))!
tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left)
tester.waitForTappableViewWithAccessibilityLabel("Show Tabs")
}
}
class SimplePageServer {
class func getPageData(name: String, ext: String = "html") -> String {
var pageDataPath = NSBundle(forClass: self).pathForResource(name, ofType: ext)!
return NSString(contentsOfFile: pageDataPath, encoding: NSUTF8StringEncoding, error: nil)! as String
}
class func start() -> String {
let webServer: GCDWebServer = GCDWebServer()
webServer.addHandlerForMethod("GET", path: "/image.png", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
let img = UIImagePNGRepresentation(UIImage(named: "back"))
return GCDWebServerDataResponse(data: img, contentType: "image/png")
}
webServer.addHandlerForMethod("GET", path: "/noTitle.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
return GCDWebServerDataResponse(HTML: self.getPageData("noTitle"))
}
webServer.addHandlerForMethod("GET", path: "/numberedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
var pageData = self.getPageData("numberedPage")
let page = (request.query["page"] as! String).toInt()!
pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description)
return GCDWebServerDataResponse(HTML: pageData as String)
}
if !webServer.startWithPort(0, bonjourName: nil) {
XCTFail("Can't start the GCDWebServer")
}
let webRoot = "http://localhost:\(webServer.port)"
return webRoot
}
}
|
mpl-2.0
|
31975b9833dc93b707c9e30b2ea8dde0
| 43.814516 | 163 | 0.674825 | 5.247403 | false | true | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/Components/SelectionScreen/Accessibility+SelectionScreen.swift
|
1
|
548
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
extension Accessibility.Identifier {
enum SelectionScreen {
private static let prefix = "SelectionScreen."
static let imageViewPrefix = "\(prefix)imageView."
static let titleLabelPrefix = "\(prefix)titleLabel."
static let descriptionLabelPrefix = "\(prefix)titleLabel."
static let selectionImageViewPrefix = "\(prefix)selectionImageViewPrefix."
static let selectionCellPrefix = "\(prefix)selectionCell."
}
}
|
lgpl-3.0
|
e6feaba5dc34c875ac4c62bbe3055fa0
| 38.071429 | 82 | 0.711152 | 5.31068 | false | false | false | false |
iOSWizards/AwesomeMedia
|
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestRendition.swift
|
1
|
2385
|
//
// QuestRendition.swift
// AwesomeCore
//
// Created by Evandro Harrison Hoffmann on 11/2/17.
//
import Foundation
public struct QuestRendition: Codable, Equatable {
public let contentType: String?
public let duration: Double?
public let edgeUrl: String?
public let filesize: Int?
public let id: String?
public let name: String?
public let overmindId: String?
public let secure: Bool?
public let status: String?
public let thumbnailUrl: String?
public let url: String?
public let assetId: String? // FK to the CDAsset
init(contentType: String?, duration: Double?, edgeUrl: String?, filesize: Int?,
id: String?, name: String?, overmindId: String?, secure: Bool?, status: String?,
thumbnailUrl: String?, url: String?, assetId: String? = nil) {
self.contentType = contentType
self.duration = duration
self.edgeUrl = edgeUrl
self.filesize = filesize
self.id = id
self.name = name
self.overmindId = overmindId
self.secure = secure
self.status = status
self.thumbnailUrl = thumbnailUrl
self.url = url
self.assetId = assetId
}
}
// MARK: - JSON Key
public struct QuestRenditions: Codable {
public let renditions: [QuestRendition]
}
// MARK: - Equatable
extension QuestRendition {
public static func ==(lhs: QuestRendition, rhs: QuestRendition) -> Bool {
if lhs.contentType != rhs.contentType {
return false
}
if lhs.duration != rhs.duration {
return false
}
if lhs.edgeUrl != rhs.edgeUrl {
return false
}
if lhs.filesize != rhs.filesize {
return false
}
if lhs.id != rhs.id {
return false
}
if lhs.name != rhs.name {
return false
}
if lhs.overmindId != rhs.overmindId {
return false
}
if lhs.secure != rhs.secure {
return false
}
if lhs.status != rhs.status {
return false
}
if lhs.thumbnailUrl != rhs.thumbnailUrl {
return false
}
if lhs.url != rhs.url {
return false
}
if lhs.assetId != rhs.assetId {
return false
}
return true
}
}
|
mit
|
bb9e5baa7f14ad81759cd61436da4b3f
| 24.645161 | 89 | 0.565199 | 4.525617 | false | false | false | false |
yanif/circator
|
MetabolicCompass/NutritionManager/View/FoodItemActionView.swift
|
1
|
3103
|
//
// FoodItemActionView.swift
// MetabolicCompassNutritionManager
//
// Created by Edwin L. Whitman on 7/30/16.
// Copyright © 2016 Edwin L. Whitman. All rights reserved.
//
import UIKit
class FoodItemActionView : UIPresentSubview {
var foodItem : FoodItem!
var proceedToAction : (Void->Void)?
var proceedToActionButton : UIButton!
convenience init(foodItem: FoodItem) {
self.init(frame: CGRect.zero)
self.foodItem = foodItem
self.configureView()
}
func configureView() {
self.proceedToActionButton = {
let button = UIButton()
button.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
button.translatesAutoresizingMaskIntoConstraints = false
button.clipsToBounds = true
button.addTarget(self, action: #selector(FoodItemActionView.proceedToAction(_:)), forControlEvents: .TouchUpInside)
button.setTitle("Add to...", forState: .Normal)
button.titleLabel?.font = UIFont.systemFontOfSize(24, weight: UIFontWeightMedium)
return button
}()
self.addSubview(self.proceedToActionButton)
let proceedToActionButtonConstraints : [NSLayoutConstraint] = [
self.proceedToActionButton.leftAnchor.constraintEqualToAnchor(self.leftAnchor),
self.proceedToActionButton.rightAnchor.constraintEqualToAnchor(self.rightAnchor),
self.proceedToActionButton.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor),
self.proceedToActionButton.heightAnchor.constraintEqualToConstant(60)
]
self.addConstraints(proceedToActionButtonConstraints)
let foodItemView = UIViewWithBlurredBackground(view: FoodItemSummaryView(foodItem: self.foodItem), withBlurEffectStyle: .Light)
foodItemView.translatesAutoresizingMaskIntoConstraints = false
foodItemView.clipsToBounds = true
foodItemView.layer.cornerRadius = 15
foodItemView.layer.shadowColor = UIColor.blackColor().CGColor
foodItemView.layer.shadowRadius = 15
foodItemView.layer.shadowOffset = CGSize.zero
foodItemView.layer.shadowOpacity = 0.5
self.addSubview(foodItemView)
let foodItemViewConstraints : [NSLayoutConstraint] = [
foodItemView.leftAnchor.constraintEqualToAnchor(self.leftAnchor),
foodItemView.rightAnchor.constraintEqualToAnchor(self.rightAnchor),
foodItemView.topAnchor.constraintEqualToAnchor(self.topAnchor),
foodItemView.bottomAnchor.constraintEqualToAnchor(self.proceedToActionButton.topAnchor, constant: -15)
]
self.addConstraints(foodItemViewConstraints)
}
func proceedToAction(sender: AnyObject) {
self.proceedToAction?()
}
override func layoutSubviews() {
super.layoutSubviews()
self.proceedToActionButton.layer.cornerRadius = self.proceedToActionButton.bounds.height/2
}
}
|
apache-2.0
|
cbf44660f7dac92604c26b565f7c41cf
| 37.7875 | 135 | 0.682141 | 5.579137 | false | false | false | false |
NickAger/elm-slider
|
ServerSlider/WebSocketServer/Packages/CYAJL-0.14.0/Tests/YAJLTests/ParserPerformance.swift
|
2
|
812
|
import XCTest
import YAJL
fileprivate let n = 5
class ParserBenchmarks: XCTestCase {
func testParseLargeJson() {
let data = loadFixture("large")
measure {
for _ in 0..<n {
_ = try! JSONParser.parse(data)
}
}
}
func testParseLargeMinJson() {
let data = loadFixture("large_min")
measure {
for _ in 0..<n {
_ = try! JSONParser.parse(data)
}
}
}
func testParseInsaneJson() {
let data = loadFixture("insane")
measure {
_ = try! JSONParser.parse(data)
}
}
}
#if os(Linux)
extension ParserBenchmarks: XCTestCaseProvider {
var allTests : [(String, () throws -> Void)] {
return [
("testParseLargeJson", testParseLargeJson),
("testParseLargeMinJson", testParseLargeMinJson),
]
}
}
#endif
|
mit
|
2d53058c7e2e347f52081e1cfb53648c
| 14.320755 | 55 | 0.592365 | 3.812207 | false | true | false | false |
endoze/BaseTask
|
BaseTaskSpecs/JSONResponseParserSpecs.swift
|
1
|
1013
|
//
// JSONResponseParserSpecs.swift
// BaseTask
//
// Created by Endoze on 4/28/16.
// Copyright © 2016 Chris Stephan. All rights reserved.
//
import Quick
import Nimble
import BaseTask
class JSONResponseParserSpecs: QuickSpec {
override func spec() {
describe("JSONResponseParser") {
describe("parsedObject") {
context("when data is nil") {
it("returns nil") {
let parser = JSONResponseParser()
let value = parser.parsedObject(nil)
expect(value).to(beNil())
}
}
context("when data is not nil") {
it("returns a dictionary from the NSData") {
let parser = JSONResponseParser()
let dictionary = ["woooo": "hoooo"]
let data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted)
let value = parser.parsedObject(data) as! [String: String]
expect(value).to(equal(dictionary))
}
}
}
}
}
}
|
mit
|
8d0742dc63ec8cc0fdbbc605beb30371
| 24.325 | 103 | 0.589921 | 4.419214 | false | false | false | false |
crossroadlabs/Boilerplate
|
Tests/BoilerplateTests/FunctionalTests.swift
|
1
|
2380
|
//
// FunctionalTests.swift
// Boilerplate
//
// Created by Daniel Leping on 28/02/2017.
// Copyright © 2017 Crossroad Labs, LTD. All rights reserved.
//
import Foundation
import XCTest
import Boilerplate
func fthree(b:Bool, i:Int, d:Double) -> String {
return String(b) + "_" + String(i) + "_" + String(d)
}
private class Decay {
private let _e:XCTestExpectation
init(e:XCTestExpectation) {
_e = e
}
deinit {
_e.fulfill()
}
}
private extension Decay {
func intToString(i:Int) -> String {
return String(i)
}
func fullfill(e:XCTestExpectation) {
e.fulfill()
}
}
class FunctionalTests: XCTestCase {
//TODO: add more of test coverage
func testApply() {
let fbi = (__, __, 1.0) |> fthree
let fi = (true, __, 1.0) |> fthree
XCTAssertEqual(fbi(false, 0), "false_0_1.0")
XCTAssertEqual(fi(0), "true_0_1.0")
XCTAssertEqual((false, 0, 0.0) |> fthree, "false_0_0.0")
}
func testCurry() {
let cthree = curry(fthree)
let uthree = uncurry(cthree)
let u2three:(Bool, Int, Double)->String = uncurry(cthree)
XCTAssertEqual(cthree(false)(0)(1.0), "false_0_1.0")
XCTAssertEqual(0.0 |> (false, 0) |> uthree, "false_0_0.0")
XCTAssertEqual((false, 0, 0.0) |> u2three, "false_0_0.0")
}
func testWeakApply() {
let e = self.expectation(description: "main")
var decay:Decay! = Decay(e: e)
let iToS = decay ~> Decay.intToString
let ff = decay ~> Decay.fullfill
ff(self.expectation(description: "inner"))
let s1 = iToS(5)
XCTAssertNotNil(s1)
XCTAssertEqual("5", s1!)
decay = nil
self.waitForExpectations(timeout: 0, handler: nil)
let s2 = iToS(6)
XCTAssertNil(s2)
}
func testTupleFlatten() {
let three = ((true, 1), 0.0)
XCTAssertEqual("true_1_0.0", flatten(three) |> fthree)
}
func testTuplify() {
let tthree = tuplify(fthree)
let tuple = (false, 1, 0.0)
XCTAssertEqual("false_1_0.0", tuple |> tthree)
XCTAssertEqual("false_1_0.0", tthree(tuple))
XCTAssertEqual("false_1_0.0", tuplify(fthree)(tuple))
}
}
|
apache-2.0
|
dc23a22ae1993b560d99b2ca541b7322
| 23.525773 | 66 | 0.543506 | 3.50885 | false | true | false | false |
GianniCarlo/Audiobook-Player
|
Shared/Models/Migrations/DataMigrationManager.swift
|
1
|
9505
|
//
// DataMigrationManager.swift
// BookPlayer
//
// Created by Gianni Carlo on 19/2/21.
// Copyright © 2021 Tortuga Power. All rights reserved.
//
import CoreData
import Foundation
final class DataMigrationManager {
let enableMigrations: Bool
let modelName: String
static let storeName = "BookPlayer"
let loadCompletionHandler: (NSPersistentStoreDescription, Error?) -> Void
var stack: CoreDataStack {
guard self.enableMigrations,
!self.store(at: DataMigrationManager.storeURL, isCompatibleWithModel: self.currentModel) else {
return CoreDataStack(modelName: self.modelName, loadCompletionHandler: self.loadCompletionHandler)
}
self.performMigration()
return CoreDataStack(modelName: self.modelName, loadCompletionHandler: self.loadCompletionHandler)
}
private var applicationSupportURL: URL {
let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory,
.userDomainMask, true)
.first
return URL(fileURLWithPath: path!)
}
private static var storeURL: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Constants.ApplicationGroupIdentifier)!.appendingPathComponent("\(DataMigrationManager.storeName).sqlite")
private var storeModel: NSManagedObjectModel? {
return NSManagedObjectModel.modelVersionsFor(modelNamed: self.modelName)
.filter {
self.store(at: DataMigrationManager.storeURL, isCompatibleWithModel: $0)
}.first
}
private lazy var currentModel: NSManagedObjectModel = .model(named: self.modelName)
init(modelNamed: String, enableMigrations: Bool = false, loadCompletionHandler: @escaping (NSPersistentStoreDescription, Error?) -> Void) {
self.modelName = modelNamed
self.enableMigrations = enableMigrations
self.loadCompletionHandler = loadCompletionHandler
}
private func store(at storeURL: URL, isCompatibleWithModel model: NSManagedObjectModel) -> Bool {
let storeMetadata = self.metadataForStoreAtURL(storeURL: storeURL)
return model.isConfiguration(withName: nil, compatibleWithStoreMetadata: storeMetadata)
}
private func metadataForStoreAtURL(storeURL: URL) -> [String: Any] {
let metadata: [String: Any]
do {
metadata = try NSPersistentStoreCoordinator
.metadataForPersistentStore(ofType: NSSQLiteStoreType,
at: storeURL, options: nil)
} catch {
metadata = [:]
print("Error retrieving metadata for store at URL: \(storeURL): \(error)")
}
return metadata
}
private func migrateStoreAt(URL storeURL: URL,
fromModel from: NSManagedObjectModel,
toModel to: NSManagedObjectModel,
mappingModel: NSMappingModel? = nil) {
let migrationManager = NSMigrationManager(sourceModel: from, destinationModel: to)
let migrationMappingModel = try? mappingModel
?? NSMappingModel.inferredMappingModel(forSourceModel: from, destinationModel: to)
let targetURL = storeURL.deletingLastPathComponent()
let destinationName = storeURL.lastPathComponent + "~1"
let destinationURL = targetURL.appendingPathComponent(destinationName)
if FileManager.default.fileExists(atPath: destinationURL.path) {
try? FileManager.default.removeItem(at: destinationURL)
}
let success: Bool
do {
try migrationManager.migrateStore(from: storeURL,
sourceType: NSSQLiteStoreType,
options: nil,
with: migrationMappingModel,
toDestinationURL: destinationURL,
destinationType: NSSQLiteStoreType,
destinationOptions: nil)
success = true
} catch {
success = false
fatalError("Migration failed \(error), \(error.localizedDescription)")
}
if success {
let fileManager = FileManager.default
let wal = storeURL.lastPathComponent + "-wal"
let shm = storeURL.lastPathComponent + "-shm"
let destinationWal = targetURL
.appendingPathComponent(wal)
let destinationShm = targetURL
.appendingPathComponent(shm)
// cleanup in case
try? fileManager.removeItem(at: destinationWal)
try? fileManager.removeItem(at: destinationShm)
do {
try fileManager.removeItem(at: storeURL)
try fileManager.moveItem(at: destinationURL, to: storeURL)
} catch {
fatalError("Error moving database: \(error), \(error.localizedDescription)")
}
}
}
class func cleanupStoreFile() {
let storeURL = DataMigrationManager.storeURL
let fileManager = FileManager.default
let wal = storeURL.appendingPathComponent("-wal")
let shm = storeURL.appendingPathComponent("-shm")
// cleanup in case
try? fileManager.removeItem(at: wal)
try? fileManager.removeItem(at: shm)
try? fileManager.removeItem(at: storeURL)
}
func performMigration() {
guard let storeModel = self.storeModel else { return }
if storeModel.isVersion1 {
let destinationModel = NSManagedObjectModel.version2
let mapPath = Bundle.main.path(forResource: "MappingModel_v1_to_v2", ofType: "cdm")!
let mapUrl = URL(fileURLWithPath: mapPath)
let mappingModel = NSMappingModel(contentsOf: mapUrl)
self.migrateStoreAt(URL: DataMigrationManager.storeURL,
fromModel: storeModel,
toModel: destinationModel,
mappingModel: mappingModel)
self.performMigration()
} else if storeModel.isVersion2 {
let destinationModel = NSManagedObjectModel.version3
let mapPath = Bundle.main.path(forResource: "MappingModel_v2_to_v3", ofType: "cdm")!
let mapUrl = URL(fileURLWithPath: mapPath)
let mappingModel = NSMappingModel(contentsOf: mapUrl)
self.migrateStoreAt(URL: DataMigrationManager.storeURL,
fromModel: storeModel,
toModel: destinationModel,
mappingModel: mappingModel)
self.performMigration()
} else if storeModel.isVersion3 {
let destinationModel = NSManagedObjectModel.version4
let mapPath = Bundle.main.path(forResource: "MappingModel_v3_to_v4", ofType: "cdm")!
let mapUrl = URL(fileURLWithPath: mapPath)
let mappingModel = NSMappingModel(contentsOf: mapUrl)
self.migrateStoreAt(URL: DataMigrationManager.storeURL,
fromModel: storeModel,
toModel: destinationModel,
mappingModel: mappingModel)
// Migrate folder hierarchy
self.migrateFolderHierarchy()
// Migrate books names
self.migrateBooks()
}
}
}
extension NSManagedObjectModel {
private class func modelURLs(in modelFolder: String) -> [URL] {
return Bundle.main
.urls(forResourcesWithExtension: "mom",
subdirectory: "\(modelFolder).momd") ?? []
}
class func modelVersionsFor(modelNamed modelName: String) -> [NSManagedObjectModel] {
return self.modelURLs(in: modelName)
.compactMap(NSManagedObjectModel.init)
}
class func bookplayerModel(named modelName: String) -> NSManagedObjectModel {
let model = self.modelURLs(in: "BookPlayer")
.filter { $0.lastPathComponent == "\(modelName).mom" }
.first
.flatMap(NSManagedObjectModel.init)
return model ?? NSManagedObjectModel()
}
class var version1: NSManagedObjectModel {
return bookplayerModel(named: "Audiobook Player")
}
var isVersion1: Bool {
return self == type(of: self).version1
}
class var version2: NSManagedObjectModel {
return bookplayerModel(named: "Audiobook Player 2")
}
var isVersion2: Bool {
return self == type(of: self).version2
}
class var version3: NSManagedObjectModel {
return bookplayerModel(named: "Audiobook Player 3")
}
var isVersion3: Bool {
return self == type(of: self).version3
}
class var version4: NSManagedObjectModel {
return bookplayerModel(named: "Audiobook Player 4")
}
var isVersion4: Bool {
return self == type(of: self).version4
}
class func model(named modelName: String, in bundle: Bundle = .main) -> NSManagedObjectModel {
return bundle.url(forResource: modelName, withExtension: "momd")
.flatMap(NSManagedObjectModel.init)
?? NSManagedObjectModel()
}
}
func == (firstModel: NSManagedObjectModel,
otherModel: NSManagedObjectModel) -> Bool {
return firstModel.entitiesByName == otherModel.entitiesByName
}
|
gpl-3.0
|
e1f581a626d85a847a08ee7fa167ba6e
| 37.477733 | 216 | 0.621949 | 5.393871 | false | false | false | false |
mleiv/KeyboardUtility
|
KeyboardUtilityDemo/KeyboardUtilityDemo/ViewController1.swift
|
1
|
3235
|
//
// ViewController1.swift
// KeyboardUtilityDemo
//
// Created by Emily Ivie on 4/19/15.
//
//
import UIKit
class ViewController1: UIViewController, KeyboardUtilityDelegate {
@IBOutlet weak var formLabel: UILabel!
@IBOutlet weak var formErrorLabel: UILabel!
@IBOutlet weak var field1: UITextField!
@IBOutlet weak var field2: UITextField!
@IBOutlet weak var field3: UITextField!
@IBOutlet weak var field4: UITextField!
@IBOutlet weak var field5: UITextField!
@IBOutlet weak var errorField2Label: UILabel!
@IBOutlet weak var errorField3Label: UILabel!
// lazy inittialize keyboard utility here:
lazy var keyboardUtility: KeyboardUtility = {
return KeyboardUtility(delegate: self)
}()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// start keyboard when the view is visible:
keyboardUtility.start()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
// stop keyboard when the view is not visible:
keyboardUtility.stop()
}
// require delegate property here:
var textFields: [UITextField] {
return [
field1,
field2,
field3,
field4,
field5,
]
}
// optional delegate functions here:
func textFieldShouldEndEditing(textField:UITextField) -> Bool {
// validate the fields here
if textField == field2 {
if textField.text?.isEmpty != false {
errorField2Label.hidden = true
return true
} else if let value = Int(textField.text ?? "") {
errorField2Label.hidden = true
return true
} else {
// error, not a number
errorField2Label.hidden = false
return false
}
}
if textField == field3 {
if textField.text?.isEmpty != false {
errorField3Label.hidden = true
return true
} else if (textField.text?.characters.count ?? 0) <= 1 {
errorField3Label.hidden = true
return true
} else {
// error, too long
errorField3Label.hidden = false
return false
}
}
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// decide if we are finished with form here
if textField == field5 {
var foundEmptyFields = 0
for field in textFields {
if field.text?.isEmpty != false {
foundEmptyFields++
}
}
if foundEmptyFields > 0 {
formErrorLabel.text = "Error: \(foundEmptyFields) Empty Fields"
formLabel.hidden = true
formErrorLabel.hidden = false
return false
} else {
formLabel.hidden = false
formErrorLabel.hidden = true
}
//
// submit form here ...
//
}
return true
}
}
|
mit
|
d24d88128372783a9c16b058e6094fb0
| 28.678899 | 79 | 0.545595 | 5.143084 | false | false | false | false |
aidenluo177/GitHubber
|
GitHubber/Pods/CoreStore/CoreStore/Observing/ObjectMonitor.swift
|
1
|
12584
|
//
// ObjectMonitor.swift
// CoreStore
//
// Copyright (c) 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - ObjectMonitor
/**
The `ObjectMonitor` monitors changes to a single `NSManagedObject` instance. Observers that implement the `ObjectObserver` protocol may then register themselves to the `ObjectMonitor`'s `addObserver(_:)` method:
let monitor = CoreStore.monitorObject(object)
monitor.addObserver(self)
The created `ObjectMonitor` instance needs to be held on (retained) for as long as the object needs to be observed.
Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles.
*/
@available(OSX, unavailable)
public final class ObjectMonitor<T: NSManagedObject> {
// MARK: Public
/**
Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted.
*/
public var object: T? {
return self.fetchedResultsController.fetchedObjects?.first as? T
}
/**
Returns `true` if the `NSManagedObject` instance being observed still exists, or `false` if the object was already deleted.
*/
public var isObjectDeleted: Bool {
return self.object?.managedObjectContext == nil
}
/**
Registers an `ObjectObserver` to be notified when changes to the receiver's `object` are made.
To prevent retain-cycles, `ObjectMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `addObserver(_:)` multiple times on the same observer is safe, as `ObjectMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: an `ObjectObserver` to send change notifications to
*/
public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
CoreStore.assert(
NSThread.isMainThread(),
"Attempted to add an observer of type \(typeName(observer)) outside the main thread."
)
self.removeObserver(observer)
self.registerChangeNotification(
&self.willChangeObjectKey,
name: ObjectMonitorWillChangeObjectNotification,
toObserver: observer,
callback: { [weak observer] (monitor) -> Void in
guard let object = monitor.object, let observer = observer else {
return
}
observer.objectMonitor(monitor, willUpdateObject: object)
}
)
self.registerObjectNotification(
&self.didDeleteObjectKey,
name: ObjectMonitorDidDeleteObjectNotification,
toObserver: observer,
callback: { [weak observer] (monitor, object) -> Void in
guard let observer = observer else {
return
}
observer.objectMonitor(monitor, didDeleteObject: object)
}
)
self.registerObjectNotification(
&self.didUpdateObjectKey,
name: ObjectMonitorDidUpdateObjectNotification,
toObserver: observer,
callback: { [weak self, weak observer] (monitor, object) -> Void in
guard let strongSelf = self, let observer = observer else {
return
}
let previousCommitedAttributes = strongSelf.lastCommittedAttributes
let currentCommitedAttributes = object.committedValuesForKeys(nil) as! [String: NSObject]
var changedKeys = Set<String>()
for key in currentCommitedAttributes.keys {
if previousCommitedAttributes[key] != currentCommitedAttributes[key] {
changedKeys.insert(key)
}
}
strongSelf.lastCommittedAttributes = currentCommitedAttributes
observer.objectMonitor(
monitor,
didUpdateObject: object,
changedPersistentKeys: changedKeys
)
}
)
}
/**
Unregisters an `ObjectObserver` from receiving notifications for changes to the receiver's `object`.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
- parameter observer: an `ObjectObserver` to unregister notifications to
*/
public func removeObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
CoreStore.assert(
NSThread.isMainThread(),
"Attempted to remove an observer of type \(typeName(observer)) outside the main thread."
)
let nilValue: AnyObject? = nil
setAssociatedRetainedObject(nilValue, forKey: &self.willChangeObjectKey, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteObjectKey, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &self.didUpdateObjectKey, inObject: observer)
}
// MARK: Internal
internal init(dataStack: DataStack, object: T) {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = object.entity
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.sortDescriptors = []
fetchRequest.includesPendingChanges = false
fetchRequest.shouldRefreshRefetchedObjects = true
let fetchedResultsController = NSFetchedResultsController(
dataStack: dataStack,
fetchRequest: fetchRequest,
fetchClauses: [Where("SELF", isEqualTo: object.objectID)]
)
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate()
self.fetchedResultsController = fetchedResultsController
self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate
self.parentStack = dataStack
fetchedResultsControllerDelegate.handler = self
fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController
try! fetchedResultsController.performFetch()
self.lastCommittedAttributes = (self.object?.committedValuesForKeys(nil) as? [String: NSObject]) ?? [:]
}
deinit {
self.fetchedResultsControllerDelegate.fetchedResultsController = nil
}
// MARK: Private
private let fetchedResultsController: NSFetchedResultsController
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate
private var lastCommittedAttributes = [String: NSObject]()
private weak var parentStack: DataStack?
private var willChangeObjectKey: Void?
private var didDeleteObjectKey: Void?
private var didUpdateObjectKey: Void?
private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
guard let strongSelf = self else {
return
}
callback(monitor: strongSelf)
}
),
forKey: notificationKey,
inObject: observer
)
}
private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>, object: T) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
guard let strongSelf = self,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T else {
return
}
callback(monitor: strongSelf, object: object)
}
),
forKey: notificationKey,
inObject: observer
)
}
}
// MARK: - ObjectMonitor: Equatable
@available(OSX, unavailable)
public func ==<T: NSManagedObject>(lhs: ObjectMonitor<T>, rhs: ObjectMonitor<T>) -> Bool {
return lhs === rhs
}
@available(OSX, unavailable)
extension ObjectMonitor: Equatable { }
// MARK: - ObjectMonitor: FetchedResultsControllerHandler
@available(OSX, unavailable)
extension ObjectMonitor: FetchedResultsControllerHandler {
// MARK: FetchedResultsControllerHandler
internal func controllerWillChangeContent(controller: NSFetchedResultsController) {
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorWillChangeObjectNotification,
object: self
)
}
internal func controllerDidChangeContent(controller: NSFetchedResultsController) { }
internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorDidDeleteObjectNotification,
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
case .Update:
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorDidUpdateObjectNotification,
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
default:
break
}
}
internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { }
internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? {
return sectionName
}
}
private let ObjectMonitorWillChangeObjectNotification = "ObjectMonitorWillChangeObjectNotification"
private let ObjectMonitorDidDeleteObjectNotification = "ObjectMonitorDidDeleteObjectNotification"
private let ObjectMonitorDidUpdateObjectNotification = "ObjectMonitorDidUpdateObjectNotification"
private let UserInfoKeyObject = "UserInfoKeyObject"
|
mit
|
935b92a1d333a69ecf04309be4bd8445
| 37.839506 | 220 | 0.641211 | 5.93865 | false | false | false | false |
open-telemetry/opentelemetry-swift
|
Sources/Exporters/DatadogExporter/Metrics/MetricEncoder.swift
|
1
|
2199
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
internal struct DDMetricPoint {
/// Log attributes received from the user. They are subject for sanitization.
let timestamp: Date
/// Log attributes added internally by the SDK. They are not a subject for sanitization.
let value: Double
}
internal struct DDMetric: Encodable {
var name: String
var points: [DDMetricPoint]
var type: String?
var host: String?
var interval: Int64?
var tags: [String]
func encode(to encoder: Encoder) throws {
try MetricEncoder().encode(self, to: encoder)
}
}
/// Encodes `DDMetric` to given encoder.
internal struct MetricEncoder {
/// Coding keys for permanent `Metric` attributes.
enum StaticCodingKeys: String, CodingKey {
// MARK: - Attributes
case name = "metric"
case points
case host
case interval
case tags
case type
}
/// Coding keys for dynamic `Metric` attributes specified by user.
private struct DynamicCodingKey: CodingKey {
var stringValue: String
var intValue: Int?
init?(stringValue: String) { self.stringValue = stringValue }
init?(intValue: Int) { return nil }
init(_ string: String) { self.stringValue = string }
}
func encode(_ metric: DDMetric, to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StaticCodingKeys.self)
try container.encode(metric.name, forKey: .name)
var points = [[Double]]()
metric.points.forEach {
points.append([$0.timestamp.timeIntervalSince1970.rounded(), $0.value])
}
try container.encode(points, forKey: .points)
if metric.type != nil {
try container.encode(metric.type, forKey: .type)
}
if metric.host != nil {
try container.encode(metric.host, forKey: .host)
}
if metric.interval != nil {
try container.encode(metric.interval, forKey: .interval)
}
if !metric.tags.isEmpty {
try container.encode(metric.tags, forKey: .tags)
}
}
}
|
apache-2.0
|
e2c922ae69952bb19acc42712ebfefcf
| 29.123288 | 92 | 0.627103 | 4.389222 | false | false | false | false |
RobertGummesson/BuildTimeAnalyzer-for-Xcode
|
BuildTimeAnalyzer/CompileMeasure.swift
|
1
|
2297
|
//
// CompileMeasure.swift
// BuildTimeAnalyzer
//
import Foundation
@objcMembers class CompileMeasure: NSObject {
dynamic var time: Double
var path: String
var code: String
dynamic var filename: String
var references: Int
private var locationArray: [Int]
public enum Order: String {
case filename
case time
}
var fileAndLine: String {
return "\(filename):\(locationArray[0])"
}
var fileInfo: String {
return "\(fileAndLine):\(locationArray[1])"
}
var location: Int {
return locationArray[0]
}
var timeString: String {
return String(format: "%.1fms", time)
}
init?(time: Double, rawPath: String, code: String, references: Int) {
let untrimmedFilename: Substring
if let lastIdx = rawPath.lastIndex(of: "/") {
untrimmedFilename = rawPath.suffix(from: rawPath.index(after: lastIdx))
} else {
untrimmedFilename = rawPath[...]
}
let filepath = rawPath.prefix(while: {$0 != ":"})
let filename = untrimmedFilename.prefix(while: {$0 != ":"})
let locations = untrimmedFilename.split(separator: ":").dropFirst().compactMap({Int(String($0))})
guard locations.count == 2 else { return nil }
self.time = time
self.code = code
self.path = String(filepath)
self.filename = String(filename)
self.locationArray = locations
self.references = references
}
init?(rawPath: String, time: Double) {
let untrimmedFilename = rawPath.split(separator: "/").map(String.init).last
guard let filepath = rawPath.split(separator: ":").map(String.init).first,
let filename = untrimmedFilename?.split(separator: ":").map(String.init).first else { return nil }
self.time = time
self.code = ""
self.path = filepath
self.filename = filename
self.locationArray = [1,1]
self.references = 1
}
subscript(column: Int) -> String {
switch column {
case 0:
return timeString
case 1:
return fileInfo
case 2:
return "\(references)"
default:
return code
}
}
}
|
mit
|
d01ecbc703943558895795dabfbf55a3
| 26.023529 | 110 | 0.57771 | 4.350379 | false | false | false | false |
qvacua/vimr
|
Commons/Sources/Commons/FoundationCommons.swift
|
1
|
4145
|
/**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
import os
public extension Array where Element: Hashable {
// From https://stackoverflow.com/a/46354989
func uniqued() -> [Element] {
var seen = Set<Element>()
return self.filter { seen.insert($0).inserted }
}
}
public extension Array {
func data() -> Data { self.withUnsafeBufferPointer(Data.init) }
}
public extension RandomAccessCollection where Index == Int {
func parallelMap<T>(chunkSize: Int = 1, _ transform: @escaping (Element) -> T) -> [T] {
let count = self.count
guard count > chunkSize else { return self.map(transform) }
var result = [T?](repeating: nil, count: count)
// If we don't use Array.withUnsafeMutableBufferPointer,
// then we get crashes.
result.withUnsafeMutableBufferPointer { pointer in
if chunkSize == 1 {
DispatchQueue.concurrentPerform(iterations: count) { i in pointer[i] = transform(self[i]) }
} else {
let chunkCount = Int(ceil(Double(self.count) / Double(chunkSize)))
DispatchQueue.concurrentPerform(iterations: chunkCount) { chunkIndex in
let start = Swift.min(chunkIndex * chunkSize, count)
let end = Swift.min(start + chunkSize, count)
(start..<end).forEach { i in pointer[i] = transform(self[i]) }
}
}
}
return result.map { $0! }
}
func groupedRanges<T: Equatable>(with marker: (Element) -> T) -> [ClosedRange<Index>] {
if self.isEmpty { return [] }
if self.count == 1 { return [self.startIndex...self.startIndex] }
var result = [ClosedRange<Index>]()
result.reserveCapacity(self.count / 2)
let inclusiveEndIndex = self.endIndex - 1
var lastStartIndex = self.startIndex
var lastEndIndex = self.startIndex
var lastMarker = marker(self.first!) // self is not empty!
for i in self.startIndex..<self.endIndex {
let currentMarker = marker(self[i])
if lastMarker == currentMarker {
if i == inclusiveEndIndex { result.append(lastStartIndex...i) }
} else {
result.append(lastStartIndex...lastEndIndex)
lastMarker = currentMarker
lastStartIndex = i
if i == inclusiveEndIndex { result.append(i...i) }
}
lastEndIndex = i
}
return result
}
}
public extension NSRange {
static let notFound = NSRange(location: NSNotFound, length: 0)
var inclusiveEndIndex: Int { self.location + self.length - 1 }
}
public extension URL {
func isParent(of url: URL) -> Bool {
guard self.isFileURL, url.isFileURL else { return false }
let myPathComps = self.pathComponents
let targetPathComps = url.pathComponents
guard targetPathComps.count == myPathComps.count + 1 else { return false }
return Array(targetPathComps[0..<myPathComps.count]) == myPathComps
}
func isAncestor(of url: URL) -> Bool {
guard self.isFileURL, url.isFileURL else { return false }
let myPathComps = self.pathComponents
let targetPathComps = url.pathComponents
guard targetPathComps.count > myPathComps.count else { return false }
return Array(targetPathComps[0..<myPathComps.count]) == myPathComps
}
func isContained(in parentUrl: URL) -> Bool {
if parentUrl == self { return false }
let pathComps = self.pathComponents
let parentPathComps = parentUrl.pathComponents
guard pathComps.count > parentPathComps.count else { return false }
guard Array(pathComps[0..<parentPathComps.endIndex]) == parentPathComps else { return false }
return true
}
var parent: URL {
if self.path == "/" { return self }
return self.deletingLastPathComponent()
}
var shellEscapedPath: String { self.path.shellEscapedPath }
var isRegularFile: Bool {
(try? self.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile ?? false
}
var isHidden: Bool { (try? self.resourceValues(forKeys: [.isHiddenKey]))?.isHidden ?? false }
var isPackage: Bool { (try? self.resourceValues(forKeys: [.isPackageKey]))?.isPackage ?? false }
}
private let log = OSLog(subsystem: "com.qvacua.vimr.commons", category: "general")
|
mit
|
f2ab2af1d0aedf7a712aacb648b0826e
| 29.255474 | 99 | 0.672376 | 4.099901 | false | false | false | false |
drunknbass/Emby.ApiClient.Swift
|
Emby.ApiClient/apiinteraction/connectionmanager/ConnectionManager.swift
|
1
|
38968
|
//
// ConnectionManager.swift
// Emby.ApiClient
//
import Foundation
public class ConnectionManager: ConnectionManagerProtocol {
let clientCapabilities: ClientCapabilities
let apiClients = [String: ApiClient]()
let credentialProvider: CredentialProviderProtocol
let device: DeviceProtocol
let serverDiscovery: ServerDiscoveryProtocol
let connectService: ConnectService
public init(clientCapabilities: ClientCapabilities,
credentialProvider: CredentialProviderProtocol,
device: DeviceProtocol,
serverDiscovery: ServerDiscoveryProtocol,
connectService: ConnectService) {
self.clientCapabilities = clientCapabilities
self.credentialProvider = credentialProvider
self.device = device
self.serverDiscovery = serverDiscovery
self.connectService = connectService
}
public func getApiClient(item: IHasServerId) -> ApiClient? {
return getApiClient(item.serverId)
}
public func getApiClient(serverId: String) -> ApiClient? {
return apiClients[serverId]
}
public func getServerInfo(serverId: String) -> ServerInfo? {
return credentialProvider
.getCredentials()
.servers
.filter({$0.id == serverId})
.first
}
public func connect(onSuccess: (ConnectionResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func connect(server: ServerInfo, onSuccess: (ConnectionResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func connect(server: ServerInfo, options: ConnectionOptions, onSuccess: (ConnectionResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func connect(address: String, onSuccess: (ConnectionResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func logout(onSuccess: () -> Void, onError: () -> Void) {
//TODO
}
public func getAvailableServers(onSuccess: ([ServerInfo]) -> Void, onError: (ErrorType?) -> Void) {
//TODO
var serverDiscoveryFinished = false
var connectedServersFinished = false
var serverDiscoveryFailed = false
var connectedServersFailed = false
var results = [ServerInfo]()
func appendServerDiscoveryInfo(serverDiscoveryInfo: [ServerDiscoveryInfo]) {
for serverDiscoveryInfoEach in serverDiscoveryInfo {
let serverInfo = ServerInfo()
serverInfo.localAddress = serverDiscoveryInfoEach.address!
serverInfo.id = serverDiscoveryInfoEach.id!
serverInfo.name = serverDiscoveryInfoEach.name!
results.append(serverInfo)
}
}
func appendConnectUserServer(connectUserServer: [ConnectUserServer]?) {
if let connectUserServer = connectUserServer {
for connectUserServerEach in connectUserServer {
let serverInfo = ServerInfo()
serverInfo.localAddress = connectUserServerEach.getLocalAddress()
if let id = connectUserServerEach.getId() {
serverInfo.id = id
}
if let name = connectUserServerEach.getName() {
serverInfo.name = name
}
if let accessToken = connectUserServerEach.getAccessKey() {
serverInfo.accessToken = accessToken
}
results.append(serverInfo)
}
}
}
serverDiscovery.findServers(1000,
onSuccess: { (serverDiscoveryInfo: [ServerDiscoveryInfo]) -> Void in
print("serverDiscovery.findServers finished with \(serverDiscoveryInfo))")
appendServerDiscoveryInfo(serverDiscoveryInfo)
serverDiscoveryFinished = true
if connectedServersFinished {
// cannot return error if we have some results from different scan method so return error only if both methods failed
if connectedServersFailed {
onError(nil)
} else {
onSuccess(results)
}
}
}, onError: { (error) -> Void in
print("serverDiscovery.findServers failed with \(error))")
serverDiscoveryFinished = true
serverDiscoveryFailed = true
if connectedServersFinished {
// cannot return error if we have some results from different scan method so return error only if both methods failed
if connectedServersFailed {
onError(nil)
} else {
onSuccess(results)
}
}
} )
self.Authenticate( connectService, onSuccess: { (userId, connectAccessToken) -> Void in
let response = EmbyApiClient.Response<ConnectUserServers>()
response.completion = { (result: ConnectUserServers?) -> Void in
print("ConnectService.GetServers finished with \(result?.servers))")
appendConnectUserServer(result?.servers)
connectedServersFinished = true
if serverDiscoveryFinished {
onSuccess(results)
}
}
do {
try self.connectService.GetServers(userId, connectAccessToken: connectAccessToken, final: response)
} catch {
print("Failed to ConnectService.GetServers() \(error)")
// cannot return error if we have some results from different scan method so return error only if both methods failed
connectedServersFinished = true
connectedServersFailed = true
if serverDiscoveryFailed {
onError(error)
} else {
onSuccess(results)
}
}
}) { () -> Void in
connectedServersFinished = true
connectedServersFailed = true
print("Failed to ConnectService.Authenticate()")
if serverDiscoveryFinished {
// cannot return error if we have some results from different scan method so return error only if both methods failed
if serverDiscoveryFailed {
onError(nil)
} else {
onSuccess(results)
}
}
}
}
public func loginToConnect(username: String, password: String, onSuccess: () -> Void, onError: () -> Void) {
//TODO
}
public func createPin(deviceId: String, onSuccess: (PinCreationResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func getPinStatus(pin: PinCreationResult, onSuccess: (PinStatusResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func exchangePin(pin: PinCreationResult, onSuccess: (PinExchangeResult) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
public func getResgistrationInfo(featureName: String, connectedServerId: String, onSuccess: (RegistrationInfo) -> Void, onError: (ErrorType) -> Void) {
//TODO
}
//}
func Authenticate(service: ConnectService,
onSuccess:(userId: String, connectAccessToken: String) -> Void, onError:() -> Void) {
let response = EmbyApiClient.Response<ConnectAuthenticationResult>()
response.completion = { (result: ConnectAuthenticationResult?) -> Void in
print("Authenticate finished with \(result) \(result?.getAccessToken())")
if let
userId = result?.getUser()?.getId(),
connectAccessToken = result?.getAccessToken() {
onSuccess(userId: userId, connectAccessToken: connectAccessToken)
} else {
onError()
}
}
service.Authenticate("vedrano", password: "123456", response: response)
}
//package mediabrowser.apiinteraction.connectionmanager;
//
//import mediabrowser.apiinteraction.*;
//import mediabrowser.apiinteraction.connect.ConnectService;
//import mediabrowser.apiinteraction.device.IDevice;
//import mediabrowser.apiinteraction.discovery.IServerLocator;
//import mediabrowser.apiinteraction.http.HttpHeaders;
//import mediabrowser.apiinteraction.http.HttpRequest;
//import mediabrowser.apiinteraction.http.IAsyncHttpClient;
//import mediabrowser.apiinteraction.network.INetworkConnection;
//import mediabrowser.model.apiclient.*;
//import mediabrowser.model.connect.*;
//import mediabrowser.model.dto.IHasServerId;
//import mediabrowser.model.dto.UserDto;
//import mediabrowser.model.extensions.StringHelper;
//import mediabrowser.model.logging.ILogger;
//import mediabrowser.model.registration.RegistrationInfo;
//import mediabrowser.model.serialization.IJsonSerializer;
//import mediabrowser.model.session.ClientCapabilities;
//import mediabrowser.model.system.PublicSystemInfo;
//import mediabrowser.model.users.AuthenticationResult;
//
//import java.io.UnsupportedEncodingException;
//import java.security.NoSuchAlgorithmException;
//import java.util.*;
//
//public class ConnectionManager implements IConnectionManager {
//
// private ICredentialProvider credentialProvider;
// private INetworkConnection networkConnection;
// protected ILogger logger;
// private IServerLocator serverDiscovery;
// protected IAsyncHttpClient httpClient;
//
// private HashMap<String, ApiClient> apiClients = new HashMap<String, ApiClient>();
// protected IJsonSerializer jsonSerializer;
//
// protected String applicationName;
// protected String applicationVersion;
// protected IDevice device;
// protected ClientCapabilities clientCapabilities;
// protected ApiEventListener apiEventListener;
//
// private ConnectService connectService;
// private ConnectUser connectUser;
//
// public ConnectionManager(ICredentialProvider credentialProvider,
// INetworkConnection networkConnectivity,
// IJsonSerializer jsonSerializer,
// ILogger logger,
// IServerLocator serverDiscovery,
// IAsyncHttpClient httpClient,
// String applicationName,
// String applicationVersion,
// IDevice device,
// ClientCapabilities clientCapabilities,
// ApiEventListener apiEventListener) {
//
// this.credentialProvider = credentialProvider;
// networkConnection = networkConnectivity;
// this.logger = logger;
// this.serverDiscovery = serverDiscovery;
// this.httpClient = httpClient;
// this.applicationName = applicationName;
// this.applicationVersion = applicationVersion;
// this.device = device;
// this.clientCapabilities = clientCapabilities;
// this.apiEventListener = apiEventListener;
// this.jsonSerializer = jsonSerializer;
//
// connectService = new ConnectService(jsonSerializer, logger, httpClient, applicationName, applicationVersion);
//
// device.getResumeFromSleepObservable().addObserver(new DeviceResumeFromSleepObservable(this));
// }
//
// public ClientCapabilities getClientCapabilities() {
// return clientCapabilities;
// }
//
// @Override
// public ApiClient GetApiClient(IHasServerId item) {
//
// return GetApiClient(item.getServerId());
// }
//
// @Override
// public ApiClient GetApiClient(String serverId) {
//
// return apiClients.get(serverId);
// }
//
// @Override
// public ServerInfo getServerInfo(String serverId) {
//
// final ServerCredentials credentials = credentialProvider.GetCredentials();
//
// for (ServerInfo server : credentials.getServers()){
// if (StringHelper.EqualsIgnoreCase(server.getId(), serverId)){
// return server;
// }
// }
// return null;
// }
//
// @Override
// public IDevice getDevice(){
// return this.device;
// }
//
// void OnConnectUserSignIn(ConnectUser user){
//
// connectUser = user;
//
// // TODO: Fire event
// }
//
// void OnFailedConnection(Response<ConnectionResult> response){
//
// logger.Debug("No server available");
//
// ConnectionResult result = new ConnectionResult();
// result.setState(ConnectionState.Unavailable);
// result.setConnectUser(connectUser);
// response.onResponse(result);
// }
//
// void OnFailedConnection(Response<ConnectionResult> response, ArrayList<ServerInfo> servers){
//
// logger.Debug("No saved authentication");
//
// ConnectionResult result = new ConnectionResult();
//
// if (servers.size() == 0 && connectUser == null){
// result.setState(ConnectionState.ConnectSignIn);
// }
// else{
// result.setState(ConnectionState.ServerSelection);
// }
//
// result.setServers(new ArrayList<ServerInfo>());
// result.setConnectUser(connectUser);
//
// response.onResponse(result);
// }
//
// @Override
// public void Connect(final Response<ConnectionResult> response) {
//
// if (clientCapabilities.getSupportsOfflineAccess())
// {
// NetworkStatus networkAccess = networkConnection.getNetworkStatus();
// if (!networkAccess.getIsNetworkAvailable())
// {
// // TODO: for offline access
// //return await GetOfflineResult().ConfigureAwait(false);
// }
// }
//
// logger.Debug("Entering initial connection workflow");
//
// GetAvailableServers(new GetAvailableServersResponse(logger, this, response));
// }
//
// void Connect(final ArrayList<ServerInfo> servers, final Response<ConnectionResult> response){
//
// // Sort by last date accessed, descending
// Collections.sort(servers, new ServerInfoDateComparator());
// Collections.reverse(servers);
//
// if (servers.size() == 1)
// {
// Connect(servers.get(0), new ConnectionOptions(), new ConnectToSingleServerListResponse(response));
// return;
// }
//
// // Check the first server for a saved access token
// if (servers.size() == 0 || tangible.DotNetToJavaStringHelper.isNullOrEmpty(servers.get(0).getAccessToken()))
// {
// OnFailedConnection(response, servers);
// return;
// }
//
// ServerInfo firstServer = servers.get(0);
// Connect(firstServer, new ConnectionOptions(), new FirstServerConnectResponse(this, servers, response));
// }
//
// @Override
// public void Connect(final ServerInfo server,
// final Response<ConnectionResult> response) {
//
// Connect(server, new ConnectionOptions(), response);
// }
//
// @Override
// public void Connect(final ServerInfo server,
// ConnectionOptions options,
// final Response<ConnectionResult> response) {
//
// ArrayList<ConnectionMode> tests = new ArrayList<ConnectionMode>();
// tests.add(ConnectionMode.Manual);
// tests.add(ConnectionMode.Local);
// tests.add(ConnectionMode.Remote);
//
// // If we've connected to the server before, try to optimize by starting with the last used connection mode
// if (server.getLastConnectionMode() != null)
// {
// tests.remove(server.getLastConnectionMode());
// tests.add(0, server.getLastConnectionMode());
// }
//
// boolean isLocalNetworkAvailable = networkConnection.getNetworkStatus().GetIsAnyLocalNetworkAvailable();
//
// // Kick off wake on lan on a separate thread (if applicable)
// boolean sendWakeOnLan = server.getWakeOnLanInfos().size() > 0 && isLocalNetworkAvailable;
//
// if (sendWakeOnLan){
// BeginWakeServer(server);
// }
//
// long wakeOnLanSendTime = System.currentTimeMillis();
//
// TestNextConnectionMode(tests, 0, isLocalNetworkAvailable, server, wakeOnLanSendTime, options, response);
// }
//
// void TestNextConnectionMode(final ArrayList<ConnectionMode> tests,
// final int index,
// final boolean isLocalNetworkAvailable,
// final ServerInfo server,
// final long wakeOnLanSendTime,
// final ConnectionOptions options,
// final Response<ConnectionResult> response){
//
// if (index >= tests.size()){
//
// OnFailedConnection(response);
// return;
// }
//
// final ConnectionMode mode = tests.get(index);
// final String address = server.GetAddress(mode);
// boolean enableRetry = false;
// boolean skipTest = false;
// int timeout = 15000;
//
// if (mode == ConnectionMode.Local){
//
// if (!isLocalNetworkAvailable){
// logger.Debug("Skipping local connection test because local network is unavailable");
// skipTest = true;
// }
// enableRetry = true;
// timeout = 10000;
// }
//
// else if (mode == ConnectionMode.Manual){
//
// if (StringHelper.EqualsIgnoreCase(address, server.getLocalAddress())){
// logger.Debug("Skipping manual connection test because the address is the same as the local address");
// skipTest = true;
// }
// else if (StringHelper.EqualsIgnoreCase(address, server.getRemoteAddress())){
// logger.Debug("Skipping manual connection test because the address is the same as the remote address");
// skipTest = true;
// }
// }
//
// if (skipTest || tangible.DotNetToJavaStringHelper.isNullOrEmpty(address))
// {
// TestNextConnectionMode(tests, index + 1, isLocalNetworkAvailable, server, wakeOnLanSendTime, options, response);
// return;
// }
//
// TryConnect(address, timeout, new TestNextConnectionModeTryConnectResponse(this, server, tests, mode, address, timeout, options, index, isLocalNetworkAvailable, wakeOnLanSendTime, enableRetry, logger, response));
// }
//
// void OnSuccessfulConnection(final ServerInfo server,
// final PublicSystemInfo systemInfo,
// final ConnectionMode connectionMode,
// final ConnectionOptions connectionOptions,
// final Response<ConnectionResult> response) {
//
// final ServerCredentials credentials = credentialProvider.GetCredentials();
//
// if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(credentials.getConnectAccessToken()))
// {
// EnsureConnectUser(credentials, new EnsureConnectUserResponse(this, server, credentials, systemInfo, connectionMode, connectionOptions, response));
// } else {
//
// AfterConnectValidated(server, credentials, systemInfo, connectionMode, true, connectionOptions, response);
// }
// }
//
// void AddAuthenticationInfoFromConnect(final ServerInfo server,
// ConnectionMode connectionMode,
// ServerCredentials credentials,
// final EmptyResponse response){
//
// if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(server.getExchangeToken())) {
// throw new IllegalArgumentException("server");
// }
//
// logger.Debug("Adding authentication info from Connect");
//
// String url = server.GetAddress(connectionMode);
//
// url += "/emby/Connect/Exchange?format=json&ConnectUserId=" + credentials.getConnectUserId();
//
// HttpRequest request = new HttpRequest();
// request.setUrl(url);
// request.setMethod("GET");
//
// request.getRequestHeaders().put("X-MediaBrowser-Token", server.getExchangeToken());
//
// httpClient.Send(request, new ExchangeTokenResponse(jsonSerializer, server, response));
// }
//
// void AfterConnectValidated(final ServerInfo server,
// final ServerCredentials credentials,
// final PublicSystemInfo systemInfo,
// final ConnectionMode connectionMode,
// boolean verifyLocalAuthentication,
// final ConnectionOptions options,
// final Response<ConnectionResult> response){
//
// if (verifyLocalAuthentication && !tangible.DotNetToJavaStringHelper.isNullOrEmpty(server.getAccessToken()))
// {
// ValidateAuthentication(server, connectionMode, new AfterConnectValidatedResponse(this, server, credentials, systemInfo, connectionMode, options, response));
//
// return;
// }
//
// server.ImportInfo(systemInfo);
//
// if (options.getUpdateDateLastAccessed()){
// server.setDateLastAccessed(new Date());
// }
//
// server.setLastConnectionMode(connectionMode);
// credentials.AddOrUpdateServer(server);
// credentialProvider.SaveCredentials(credentials);
//
// ConnectionResult result = new ConnectionResult();
//
// result.setApiClient(GetOrAddApiClient(server, connectionMode));
// result.setState(tangible.DotNetToJavaStringHelper.isNullOrEmpty(server.getAccessToken()) ?
// ConnectionState.ServerSignIn :
// ConnectionState.SignedIn);
//
// result.getServers().add(server);
// result.getApiClient().EnableAutomaticNetworking(server, connectionMode, networkConnection);
//
// if (result.getState() == ConnectionState.SignedIn)
// {
// AfterConnected(result.getApiClient(), options);
// }
//
// response.onResponse(result);
// }
//
// @Override
// public void Connect(final String address, final Response<ConnectionResult> response) {
//
// final String normalizedAddress = NormalizeAddress(address);
//
// logger.Debug("Attempting to connect to server at %s", address);
//
// TryConnect(normalizedAddress, 15000, new ConnectToAddressResponse(this, normalizedAddress, response));
// }
//
// @Override
// public void Logout(final EmptyResponse response) {
//
// logger.Debug("Logging out of all servers");
//
// LogoutAll(new LogoutAllResponse(credentialProvider, logger, response, this));
// }
//
// void clearConnectUserAfterLogout() {
//
// if (connectUser != null){
// connectUser = null;
// }
// }
//
// private void ValidateAuthentication(final ServerInfo server, ConnectionMode connectionMode, final EmptyResponse response)
// {
// final String url = server.GetAddress(connectionMode);
//
// HttpHeaders headers = new HttpHeaders();
// headers.SetAccessToken(server.getAccessToken());
//
// final HttpRequest request = new HttpRequest();
// request.setUrl(url + "/emby/system/info?format=json");
// request.setMethod("GET");
// request.setRequestHeaders(headers);
//
// Response<String> stringResponse = new ValidateAuthenticationResponse(this, jsonSerializer, server, response, request, httpClient, url);
//
// httpClient.Send(request, stringResponse);
// }
//
// void TryConnect(String url, int timeout, final Response<PublicSystemInfo> response)
// {
// url += "/emby/system/info/public?format=json";
//
// HttpRequest request = new HttpRequest();
// request.setUrl(url);
// request.setMethod("GET");
// request.setTimeout(timeout);
//
// httpClient.Send(request, new SerializedResponse<PublicSystemInfo>(response, jsonSerializer, PublicSystemInfo.class));
// }
//
// protected ApiClient InstantiateApiClient(String serverAddress) {
//
// return new ApiClient(httpClient,
// jsonSerializer,
// logger,
// serverAddress,
// applicationName,
// applicationVersion,
// device,
// apiEventListener);
// }
//
// private ApiClient GetOrAddApiClient(ServerInfo server, ConnectionMode connectionMode)
// {
// ApiClient apiClient = apiClients.get(server.getId());
//
// if (apiClient == null){
//
// String address = server.GetAddress(connectionMode);
//
// apiClient = InstantiateApiClient(address);
//
// apiClients.put(server.getId(), apiClient);
//
// apiClient.getAuthenticatedObservable().addObserver(new AuthenticatedObserver(this, apiClient));
// }
//
// if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(server.getAccessToken()))
// {
// apiClient.ClearAuthenticationInfo();
// }
// else
// {
// apiClient.SetAuthenticationInfo(server.getAccessToken(), server.getUserId());
// }
//
// return apiClient;
// }
//
// void AfterConnected(ApiClient apiClient, ConnectionOptions options)
// {
// if (options.getReportCapabilities()){
// apiClient.ReportCapabilities(clientCapabilities, new EmptyResponse());
// }
//
// if (options.getEnableWebSocket()){
// apiClient.OpenWebSocket();
// }
// }
//
// void OnAuthenticated(final ApiClient apiClient,
// final AuthenticationResult result,
// ConnectionOptions options,
// final boolean saveCredentials)
// {
// logger.Debug("Updating credentials after local authentication");
//
// ServerInfo server = apiClient.getServerInfo();
//
// ServerCredentials credentials = credentialProvider.GetCredentials();
//
// if (options.getUpdateDateLastAccessed()){
// server.setDateLastAccessed(new Date());
// }
//
// if (saveCredentials)
// {
// server.setUserId(result.getUser().getId());
// server.setAccessToken(result.getAccessToken());
// }
// else
// {
// server.setUserId(null);
// server.setAccessToken(null);
// }
//
// credentials.AddOrUpdateServer(server);
// SaveUserInfoIntoCredentials(server, result.getUser());
// credentialProvider.SaveCredentials(credentials);
//
// AfterConnected(apiClient, options);
//
// OnLocalUserSignIn(result.getUser());
// }
//
// private void SaveUserInfoIntoCredentials(ServerInfo server, UserDto user)
// {
// ServerUserInfo info = new ServerUserInfo();
// info.setIsSignedInOffline(true);
// info.setId(user.getId());
//
// // Record user info here
// server.AddOrUpdate(info);
// }
//
// void OnLocalUserSignIn(UserDto user)
// {
// // TODO: Fire event
// }
//
// void OnLocalUserSignout(ApiClient apiClient)
// {
// // TODO: Fire event
// }
//
// public void GetAvailableServers(final Response<ArrayList<ServerInfo>> response)
// {
// logger.Debug("Getting saved servers via credential provider");
// final ServerCredentials credentials = credentialProvider.GetCredentials();
//
// final int numTasks = 2;
// final int[] numTasksCompleted = {0};
// final ArrayList<ServerInfo> foundServers = new ArrayList<ServerInfo>();
// final ArrayList<ServerInfo> connectServers = new ArrayList<ServerInfo>();
//
// Response<ArrayList<ServerInfo>> findServersResponse = new FindServersResponse(this, credentials, foundServers, connectServers, numTasksCompleted, numTasks, response);
//
// logger.Debug("Scanning network for local servers");
//
// FindServers(findServersResponse);
//
// EmptyResponse connectServersResponse = new GetConnectServersResponse(logger, connectService, credentials, foundServers, connectServers, numTasks, numTasksCompleted, response, this);
//
// if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(credentials.getConnectAccessToken()))
// {
// logger.Debug("Getting server list from Connect");
//
// EnsureConnectUser(credentials, connectServersResponse);
// }
// else{
// connectServersResponse.onError(null);
// }
// }
//
// void EnsureConnectUser(ServerCredentials credentials, final EmptyResponse response){
//
// if (connectUser != null && StringHelper.EqualsIgnoreCase(connectUser.getId(), credentials.getConnectUserId()))
// {
// response.onResponse();
// return;
// }
//
// if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(credentials.getConnectUserId()) && !tangible.DotNetToJavaStringHelper.isNullOrEmpty(credentials.getConnectAccessToken()))
// {
// this.connectUser = null;
//
// ConnectUserQuery query = new ConnectUserQuery();
//
// query.setId(credentials.getConnectUserId());
//
// connectService.GetConnectUser(query, credentials.getConnectAccessToken(), new GetConnectUserResponse(this, response));
// }
// }
//
// void OnGetServerResponse(ServerCredentials credentials,
// ArrayList<ServerInfo> foundServers,
// ArrayList<ServerInfo> connectServers,
// Response<ArrayList<ServerInfo>> response){
//
// for(ServerInfo newServer : foundServers){
//
// if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(newServer.getManualAddress())) {
// newServer.setLastConnectionMode(ConnectionMode.Local);
// }
// else {
// newServer.setLastConnectionMode(ConnectionMode.Manual);
// }
//
// credentials.AddOrUpdateServer(newServer);
// }
//
// for(ServerInfo newServer : connectServers){
//
// credentials.AddOrUpdateServer(newServer);
// }
//
// ArrayList<ServerInfo> cleanList = new ArrayList<ServerInfo>();
// ArrayList<ServerInfo> existing = credentials.getServers();
//
// for(ServerInfo server : existing){
//
// // It's not a connect server, so assume it's still valid
// if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(server.getExchangeToken()))
// {
// cleanList.add(server);
// continue;
// }
//
// boolean found = false;
//
// for(ServerInfo connectServer : connectServers){
//
// if (StringHelper.EqualsIgnoreCase(server.getId(), connectServer.getId())){
// found = true;
// break;
// }
// }
//
// if (found)
// {
// cleanList.add(server);
// }
// else{
// logger.Debug("Dropping server "+server.getName()+" - "+server.getId()+" because it's no longer in the user's Connect profile.");
// }
// }
//
// // Sort by last date accessed, descending
// Collections.sort(cleanList, new ServerInfoDateComparator());
// Collections.reverse(cleanList);
//
// credentials.setServers(cleanList);
//
// credentialProvider.SaveCredentials(credentials);
//
// ArrayList<ServerInfo> clone = new ArrayList<ServerInfo>();
// clone.addAll(credentials.getServers());
//
// response.onResponse(clone);
// }
//
// protected void FindServers(final Response<ArrayList<ServerInfo>> response)
// {
// FindServersInternal(response);
// }
//
// protected void FindServersInternal(final Response<ArrayList<ServerInfo>> response)
// {
// serverDiscovery.serverDiscoveryInfo.size()(1000, new FindServersInnerResponse(this, response));
// }
//
// void WakeAllServers()
// {
// logger.Debug("Waking all servers");
//
// for(ServerInfo server : credentialProvider.GetCredentials().getServers()){
//
// WakeServer(server, new EmptyResponse());
// }
// }
//
// private void BeginWakeServer(final ServerInfo info)
// {
// Thread thread = new Thread(new BeginWakeServerRunnable(this, info));
//
// thread.start();
// }
//
// void WakeServer(ServerInfo info, final EmptyResponse response)
// {
// logger.Debug("Waking server: %s, Id: %s", info.getName(), info.getId());
//
// ArrayList<WakeOnLanInfo> wakeList = info.getWakeOnLanInfos();
//
// final int count = wakeList.size();
//
// if (count == 0){
// logger.Debug("Server %s has no saved wake on lan profiles", info.getName());
// response.onResponse();
// return;
// }
//
// final ArrayList<EmptyResponse> doneList = new ArrayList<EmptyResponse>();
//
// for(WakeOnLanInfo wakeOnLanInfo : wakeList){
//
// WakeServer(wakeOnLanInfo, new WakeServerResponse(doneList, response));
// }
// }
//
// private void WakeServer(WakeOnLanInfo info, EmptyResponse response) {
//
// networkConnection.SendWakeOnLan(info.getMacAddress(), info.getPort(), response);
// }
//
// String NormalizeAddress(String address) throws IllegalArgumentException {
//
// if (tangible.DotNetToJavaStringHelper.isNullOrEmpty(address))
// {
// throw new IllegalArgumentException("address");
// }
//
// if (StringHelper.IndexOfIgnoreCase(address, "http") == -1)
// {
// address = "http://" + address;
// }
//
// return address;
// }
//
// private void LogoutAll(final EmptyResponse response){
//
// Object[] clientList = apiClients.values().toArray();
//
// final int count = clientList.length;
//
// if (count == 0){
// response.onResponse();
// return;
// }
//
// final ArrayList<Integer> doneList = new ArrayList<Integer>();
//
// for(Object clientObj : clientList){
//
// ApiClient client = (ApiClient)clientObj;
//
// ApiClientLogoutResponse logoutResponse = new ApiClientLogoutResponse(doneList, count, response, this, client);
//
// if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(client.getAccessToken()))
// {
// client.Logout(logoutResponse);
// }
// else {
// logoutResponse.onResponse(false);
// }
// }
//
// connectUser = null;
// }
//
// public void LoginToConnect(String username, String password, final EmptyResponse response) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//
// connectService.Authenticate(username, password, new LoginToConnectResponse(this, credentialProvider, response));
// }
//
// public void CreatePin(String deviceId, Response<PinCreationResult> response)
// {
// connectService.CreatePin(deviceId, response);
// }
//
// public void GetPinStatus(PinCreationResult pin, Response<PinStatusResult> response)
// {
// connectService.GetPinStatus(pin, response);
// }
//
// public void ExchangePin(PinCreationResult pin, final Response<PinExchangeResult> response)
// {
// connectService.ExchangePin(pin, new ExchangePinResponse(credentialProvider, response));
// }
//
// public void GetRegistrationInfo(String featureName, String connectedServerId, Response<RegistrationInfo> response) {
//
// FindServers(new GetRegistrationInfoFindServersResponse(this, featureName, connectedServerId, logger, response, credentialProvider, connectService));
// }
}
|
mit
|
6627910a14e5c716c66afdc5f3423b37
| 36.578592 | 225 | 0.569134 | 4.81443 | false | false | false | false |
mcxiaoke/learning-ios
|
cocoa_programming_for_osx/17_NSViewAndDrawing/ImageGrid/ImageGrid/MainWindowController.swift
|
1
|
618
|
//
// MainWindowController.swift
// ImageGrid
//
// Created by mcxiaoke on 16/5/5.
// Copyright © 2016年 mcxiaoke. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController {
override var windowNibName: String? {
return "MainWindowController"
}
override func windowDidLoad() {
super.windowDidLoad()
let superview = window?.contentView
let frame = NSRect(x: 40, y: 40, width: 200, height: 40)
let button = NSButton(frame:frame)
button.title = "Click Me!"
button.alignment = .Center
superview?.addSubview(button)
}
}
|
apache-2.0
|
fdab03880dfe0fd0b0dcd0c69dc43b80
| 21.777778 | 62 | 0.658537 | 4.183673 | false | false | false | false |
sai43/PullToBounce
|
PullToBounce/Example/SampleCell.swift
|
4
|
1607
|
//
// SampleCell.swift
// PullToBounce
//
// Created by Takuya Okamoto on 2015/08/12.
// Copyright (c) 2015年 Uniface. All rights reserved.
//
import UIKit
class SampleCell: UITableViewCell {
let color = UIColor.lightBlue
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let iconMock = UIView()
iconMock.backgroundColor = color
iconMock.frame = CGRect(x: 16, y: 16, width: 60, height: 60)
iconMock.layer.cornerRadius = 10
self.addSubview(iconMock)
let lineLeft:CGFloat = iconMock.frame.right + 16
let lineMargin:CGFloat = 12
let line1 = CGRect(x: lineLeft, y: 12 + lineMargin, width: 100, height: 6)
let line2 = CGRect(x: lineLeft, y: line1.bottom + lineMargin, width: 160, height: 5)
let line3 = CGRect(x: lineLeft, y: line2.bottom + lineMargin, width: 180, height: 5)
addLine(line1)
addLine(line2)
addLine(line3)
let sepalator = UIView()
sepalator.frame = CGRect(x: 0, y: 92 - 1, width: frame.width, height: 1)
sepalator.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.2)
self.addSubview(sepalator)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addLine(frame:CGRect) {
let line = UIView(frame:frame)
line.layer.cornerRadius = frame.height / 2
line.backgroundColor = color
self.addSubview(line)
}
}
|
mit
|
c0af06a115135783aa6f94f3a7d32769
| 22.602941 | 92 | 0.62243 | 3.895631 | false | false | false | false |
wangweicheng7/ClouldFisher
|
CloudFisher/Class/Square/Controller/PWFilterController.swift
|
1
|
4665
|
//
// PWFilterController.swift
// CloudFisher
//
// Created by 王炜程 on 2017/2/14.
// Copyright © 2017年 weicheng wang. All rights reserved.
//
import UIKit
class PWFilterController: UIViewController {
@IBOutlet weak var filterView: UIView!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var filterButton: UIButton!
@IBOutlet weak var filterTopConstraint: NSLayoutConstraint!
@IBOutlet weak var filterLeadingConstraint: NSLayoutConstraint!
var dataSource = [(String, [String])]()
var filterAction: ((_ appid: Int, _ version: String) -> Void)!
override func viewDidLoad() {
super.viewDidLoad()
self.filterLeadingConstraint.constant = 0
pickerView.delegate = self
pickerView.dataSource = self
// Do any additional setup after loading the view.
for x in 0...10 {
var ele: (String, [String])
ele.0 = "名字\(x)"
var tmp = [String]()
for y in 0...20 {
tmp.append("\(x).\(y)")
}
ele.1 = tmp
dataSource.append(ele)
}
pickerView.reloadAllComponents()
}
@IBAction func filterAction(_ sender: UIButton) {
UIView.animate(withDuration: 0.2, delay: 0.1, options: UIViewAnimationOptions.curveLinear, animations: {
self.filterLeadingConstraint.constant = 0
self.view.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.15) {
self.filterTopConstraint.constant = 0
self.view.layoutIfNeeded()
}
let appid = pickerView.selectedRow(inComponent: 0)
let version = pickerView.selectedRow(inComponent: 1)
filterAction(1108, "1.3.9")
dismiss(animated: true, completion: nil)
}
@IBAction func tapAction(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.2, delay: 0.1, options: UIViewAnimationOptions.curveLinear, animations: {
self.filterLeadingConstraint.constant = 0
self.view.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.15) {
self.filterTopConstraint.constant = 0
self.view.layoutIfNeeded()
}
dismiss(animated: true, completion: nil)
}
func reloadData() {
// PWRequest.request(with: <#T##String#>, parameter: <#T##[String : Any]?#>, <#T##callback: PWServiceCallback##PWServiceCallback##(Any?, Bool, Int) -> ()#>)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 0.2, delay: 0.1, options: UIViewAnimationOptions.curveLinear, animations: {
self.filterTopConstraint.constant = -180
self.view.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.15) {
self.view.alpha = 1
self.filterLeadingConstraint.constant = -(UIScreen.main.bounds.size.width - 16 - 44)
self.view.layoutIfNeeded()
}
}
init(_ filter: @escaping (_ appid: Int, _ version: String) -> Void) {
super.init(nibName: "PWFilterController", bundle: nil)
modalTransitionStyle = .crossDissolve
modalPresentationStyle = .custom
filterAction = filter
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PWFilterController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return dataSource.count
}else{
let com = pickerView.selectedRow(inComponent: 0)
return dataSource[com].1.count
}
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
if component == 0 {
return NSAttributedString(string: dataSource[row].0)
}
let com = pickerView.selectedRow(inComponent: 0)
let titles = dataSource[com].1
return NSAttributedString(string: titles[row])
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
pickerView.reloadComponent(1)
}
}
}
|
mit
|
c54282f13e5ab16658415de40ad1789e
| 32.228571 | 163 | 0.603181 | 4.85595 | false | false | false | false |
digoreis/swift-proposal-analyzer
|
swift-proposal-analyzer.playground/Pages/SE-0166.xcplaygroundpage/Contents.swift
|
1
|
117305
|
/*:
# Swift Archival & Serialization
* Proposal: [SE-0166](0166-swift-archival-serialization.md)
* Authors: [Itai Ferber](https://github.com/itaiferber), [Michael LeHew](https://github.com/mlehew), [Tony Parker](https://github.com/parkera)
* Review Manager: [Doug Gregor](https://github.com/DougGregor)
* Status: **Active review (April 6...12, 2017)**
* Associated PRs:
* [#8124](https://github.com/apple/swift/pull/8124)
* [#8125](https://github.com/apple/swift/pull/8125)
## Introduction
Foundation's current archival and serialization APIs (`NSCoding`, `NSJSONSerialization`, `NSPropertyListSerialization`, etc.), while fitting for the dynamism of Objective-C, do not always map optimally into Swift. This document lays out the design of an updated API that improves the developer experience of performing archival and serialization in Swift.
Specifically:
* It aims to provide a solution for the archival of Swift `struct` and `enum` types
* It aims to provide a more type-safe solution for serializing to external formats, such as JSON and plist
## Motivation
The primary motivation for this proposal is the inclusion of native Swift `enum` and `struct` types in archival and serialization. Currently, developers targeting Swift cannot participate in `NSCoding` without being willing to abandon `enum` and `struct` types — `NSCoding` is an `@objc` protocol, conformance to which excludes non-`class` types. This is can be limiting in Swift because small `enums` and `structs` can be an idiomatic approach to model representation; developers who wish to perform archival have to either forgo the Swift niceties that constructs like `enums` provide, or provide an additional compatibility layer between their "real" types and their archivable types.
Secondarily, we would like to refine Foundation's existing serialization APIs (`NSJSONSerialization` and `NSPropertyListSerialization`) to better match Swift's strong type safety. From experience, we find that the conversion from the unstructured, untyped data of these formats into strongly-typed data structures is a good fit for archival mechanisms, rather than taking the less safe approach that 3rd-party JSON conversion approaches have taken (described further in an appendix below).
We would like to offer a solution to these problems without sacrificing ease of use or type safety.
## Agenda
This proposal is the first stage of three that introduce different facets of a whole Swift archival and serialization API:
1. This proposal describes the basis for this API, focusing on the protocols that users adopt and interface with
2. The next stage will propose specific API for new encoders
3. The final stage will discuss how this new API will interop with `NSCoding` as it is today
[SE-0167](0167-swift-encoders.md) provides stages 2 and 3.
## Proposed solution
We will be introducing the `Encodable` and `Decodable` protocols, adoption of which will allow end user types to participate in encoding and decoding:
```swift
// Codable implies Encodable and Decodable
// If all properties are Codable, protocol implementation is automatically generated by the compiler:
public struct Location : Codable {
public let latitude: Double
public let longitude: Double
}
public enum Animal : Int, Codable {
case chicken = 1
case dog
case turkey
case cow
}
public struct Farm : Codable {
public let name: String
public let location: Location
public let animals: [Animal]
}
```
With developer participation, we will offer encoders and decoders (described in [SE-0167](0167-swift-encoders.md), not here) that take advantage of this conformance to offer type-safe serialization of user models:
```swift
let farm = Farm(name: "Old MacDonald's Farm",
location: Location(latitude: 51.621648, longitude: 0.269273),
animals: [.chicken, .dog, .cow, .turkey, .dog, .chicken, .cow, .turkey, .dog])
let payload: Data = try JSONEncoder().encode(farm)
do {
let farm = try JSONDecoder().decode(Farm.self, from: payload)
// Extracted as user types:
let coordinates = "\(farm.location.latitude, farm.location.longitude)"
} catch {
// Encountered error during deserialization
}
```
This gives developers access to their data in a type-safe manner and a recognizable interface.
## Detailed design
We will be introducing the following new types:
* `protocol Encodable` & `protocol Decodable`: Adopted by types to opt into archival. Implementation can be synthesized by the compiler in cases where all properties are also `Encodable` or `Decodable`
* `protocol CodingKey`: Adopted by types used as keys for keyed containers, replacing `String` keys with semantic types. Implementation can be synthesized by the compiler in most cases
* `protocol Encoder`: Adopted by types which can take `Encodable` values and encode them into a native format
* `protocol KeyedEncodingContainerProtocol`: Adopted by types which provide a concrete way to store encoded values by `CodingKey`. Types adopting `Encoder` should provide types conforming to `KeyedEncodingContainerProtocol` to vend
* `struct KeyedEncodingContainer<Key : CodingKey>`: A concrete type-erased box for exposing `KeyedEncodingContainerProtocol` types; this is a type consumers of the API interact with directly
* `protocol UnkeyedEncodingContainer`: Adopted by types which provide a concrete way to stored encoded values with no keys. Types adopting `Encoder` should provide types conforming to `UnkeyedEncodingContainer` to vend
* `protocol SingleValueEncodingContainer`: Adopted by types which provide a concrete way to store a single encoded value. Types adopting `Encoder` should provide types conforming to `SingleValueEncodingContainer` to vend
* `protocol Decoder`: Adopted by types which can take payloads in a native format and decode `Decodable` values out of them
* `protocol KeyedDecodingContainerProtocol`: Adopted by types which provide a concrete way to retrieve encoded values from storage by `CodingKey`. Types adopting `Decoder` should provide types conforming to `KeyedDecodingContainerProtocol` to vend
* `struct KeyedDecodingContainer<Key : CodingKey>`: A concrete type-erased box for exposing `KeyedDecodingContainerProtocol` types; this is a type consumers of the API interact with directly
* `protocol UnkeyedDecodingContainer`: Adopted by types which provide a concrete way to retrieve encoded values from storage with no keys. Types adopting `Decoder` should provide types conforming to `UnkeyedDecodingContainer` to vend
* `protocol SingleValueDecodingContainer`: Adopted by types which provide a concrete way to retrieve a single encoded value from storage. Types adopting `Decoder` should provide types conforming to `SingleValueDecodingContainer` to vend
* `struct CodingUserInfoKey`: A `String RawRepresentable struct` for representing keys to use in `Encoders`' and `Decoders`' `userInfo` dictionaries
To support user types, we expose the `Encodable` and `Decodable` protocols:
```swift
/// Conformance to `Encodable` indicates that a type can encode itself to an external representation.
public protocol Encodable {
/// Encodes `self` into the given encoder.
///
/// If `self` fails to encode anything, `encoder` will encode an empty keyed container in its place.
///
/// - parameter encoder: The encoder to write data to.
/// - throws: An error if any values are invalid for `encoder`'s format.
func encode(to encoder: Encoder) throws
}
/// Conformance to `Decodable` indicates that a type can decode itself from an external representation.
public protocol Decodable {
/// Initializes `self` by decoding from `decoder`.
///
/// - parameter decoder: The decoder to read data from.
/// - throws: An error if reading from the decoder fails, or if read data is corrupted or otherwise invalid.
init(from decoder: Decoder) throws
}
/// Conformance to `Codable` indicates that a type can convert itself into and out of an external representation.
public typealias Codable = Encodable & Decodable
```
By adopting these protocols, user types opt in to this system.
Structured types (i.e. types which encode as a collection of properties) encode and decode their properties in a keyed manner. Keys are semantic `String`-convertible `enums` which map properties to encoded names. Keys must conform to the `CodingKey` protocol:
```swift
/// Conformance to `CodingKey` indicates that a type can be used as a key for encoding and decoding.
public protocol CodingKey {
/// The string to use in a named collection (e.g. a string-keyed dictionary).
var stringValue: String { get }
/// Initializes `self` from a string.
///
/// - parameter stringValue: The string value of the desired key.
/// - returns: An instance of `Self` from the given string, or `nil` if the given string does not correspond to any instance of `Self`.
init?(stringValue: String)
/// The int to use in an indexed collection (e.g. an int-keyed dictionary).
var intValue: Int? { get }
/// Initializes `self` from an integer.
///
/// - parameter intValue: The integer value of the desired key.
/// - returns: An instance of `Self` from the given integer, or `nil` if the given integer does not correspond to any instance of `Self`.
init?(intValue: Int)
}
```
For performance, where relevant, keys may be `Int`-convertible, and `Encoders` may choose to make use of `Ints` over `Strings` as appropriate. Framework types should provide keys which have both for flexibility and performance across different types of `Encoders`.
By default, `CodingKey` conformance can be derived for `enums` which have no raw type and no associated values, or `String` or `Int` backing:
```swift
enum Keys1 : CodingKey {
case a // (stringValue: "a", intValue: nil)
case b // (stringValue: "b", intValue: nil)
// The compiler automatically generates the following:
var stringValue: String {
switch self {
case .a: return "a"
case .b: return "b"
}
}
init?(stringValue: String) {
switch stringValue {
case "a": self = .a
case "b": self = .b
default: return nil
}
}
var intValue: Int? {
return nil
}
init?(intValue: Int) {
return nil
}
}
enum Keys2 : String, CodingKey {
case c = "foo" // (stringValue: "foo", intValue: nil)
case d // (stringValue: "d", intValue: nil)
// stringValue, init?(stringValue:), intValue, and init?(intValue:) are generated by the compiler as well
}
enum Keys3 : Int, CodingKey {
case e = 4 // (stringValue: "e", intValue: 4)
case f // (stringValue: "f", intValue: 5)
case g = 9 // (stringValue: "g", intValue: 9)
// stringValue, init?(stringValue:), intValue, and init?(intValue:) are generated by the compiler as well
}
```
Coding keys which are not `enum`s, have associated values, or have other raw representations must implement these methods manually.
In addition to automatic `CodingKey` requirement synthesis for `enums`, `Encodable` & `Decodable` requirements can be automatically synthesized for certain types as well:
1. Types conforming to `Encodable` whose properties are all `Encodable` get an automatically generated `String`-backed `CodingKey` `enum` mapping properties to case names. Similarly for `Decodable` types whose properties are all `Decodable`
2. Types falling into (1) — and types which manually provide a `CodingKey` `enum` (named `CodingKeys`, directly, or via a `typealias`) whose cases map 1-to-1 to `Encodable`/`Decodable` properties by name — get automatic synthesis of `init(from:)` and `encode(to:)` as appropriate, using those properties and keys
3. Types which fall into neither (1) nor (2) will have to provide a custom key type if needed and provide their own `init(from:)` and `encode(to:)`, as appropriate
This synthesis can always be overridden by a manual implementation of any protocol requirements. Many types will either allow for automatic synthesis of all of codability (1), or provide a custom key subset and take advantage of automatic method synthesis (2).
### Encoding and Decoding
Types which are `Encodable` encode their data into a container provided by their `Encoder`:
```swift
/// An `Encoder` is a type which can encode values into a native format for external representation.
public protocol Encoder {
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func container<Key : CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key>
/// Returns an encoding container appropriate for holding multiple unkeyed values.
///
/// - returns: A new empty unkeyed container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer
/// Returns an encoding container appropriate for holding a single primitive value.
///
/// - returns: A new empty single value container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
}
// Continuing examples from before; below is automatically generated by the compiler if no customization is needed.
public struct Location : Codable {
private enum CodingKeys : CodingKey {
case latitude
case longitude
}
public func encode(to encoder: Encoder) throws {
// Generic keyed encoder gives type-safe key access: cannot encode with keys of the wrong type.
let container = encoder.container(keyedBy: CodingKeys.self)
// The encoder is generic on the key -- free key autocompletion here.
try container.encode(latitude, forKey: .latitude)
try container.encode(longitude, forKey: .longitude)
}
}
public struct Farm : Codable {
private enum CodingKeys : CodingKey {
case name
case location
case animals
}
public func encode(to encoder: Encoder) throws {
let container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(location, forKey: .location)
try container.encode(animals, forKey: .animals)
}
}
```
Similarly, `Decodable` types initialize from data read from their `Decoder`'s container:
```swift
/// A `Decoder` is a type which can decode values from a native format into in-memory representations.
public protocol Decoder {
/// Returns the data stored in `self` as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
func container<Key : CodingKey>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key>
/// Returns the data stored in `self` as represented in a container appropriate for holding values with no keys.
///
/// - returns: An unkeyed container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
func unkeyedContainer() throws -> UnkeyedDecodingContainer
/// Returns the data stored in `self` as represented in a container appropriate for holding a single primitive value.
///
/// - returns: A single value container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a single value container.
func singleValueContainer() throws -> SingleValueDecodingContainer
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
}
// Continuing examples from before; below is automatically generated by the compiler if no customization is needed.
public struct Location : Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
latitude = try container.decode(Double.self, forKey: .latitude)
longitude = try container.decode(Double.self, forKey: .longitude)
}
}
public struct Farm : Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
location = try container.decode(Location.self, forKey: .location)
animals = try container.decode([Animal].self, forKey: .animals)
}
}
```
### Keyed Containers
Keyed containers are the primary interface that most `Codable` types interact with for encoding and decoding. Through these, `Codable` types have strongly-keyed access to encoded data by using keys that are semantically correct for the operations they want to express.
Since semantically incompatible keys will rarely (if ever) share the same key type, it is impossible to mix up key types within the same container (as is possible with `String` keys), and since the type is known statically, keys get autocompletion by the compiler.
```swift
/// Conformance to `KeyedEncodingContainerProtocol` indicates that a type provides a view into an `Encoder`'s storage and is used to hold the encoded properties of an `Encodable` type in a keyed manner.
///
/// Encoders should provide types conforming to `KeyedEncodingContainerProtocol` for their format.
public protocol KeyedEncodingContainerProtocol {
associatedtype Key : CodingKey
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T : Encodable>(_ value: T?, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool?, forKey key: Key) throws
mutating func encode(_ value: Int?, forKey key: Key) throws
mutating func encode(_ value: Int8?, forKey key: Key) throws
mutating func encode(_ value: Int16?, forKey key: Key) throws
mutating func encode(_ value: Int32?, forKey key: Key) throws
mutating func encode(_ value: Int64?, forKey key: Key) throws
mutating func encode(_ value: UInt?, forKey key: Key) throws
mutating func encode(_ value: UInt8?, forKey key: Key) throws
mutating func encode(_ value: UInt16?, forKey key: Key) throws
mutating func encode(_ value: UInt32?, forKey key: Key) throws
mutating func encode(_ value: UInt64?, forKey key: Key) throws
mutating func encode(_ value: Float?, forKey key: Key) throws
mutating func encode(_ value: Double?, forKey key: Key) throws
mutating func encode(_ value: String?, forKey key: Key) throws
mutating func encode(_ value: Data?, forKey key: Key) throws
/// Encodes the given object weakly for the given key.
///
/// For `Encoder`s that implement this functionality, this will only encode the given object and associate it with the given key if it is encoded unconditionally elsewhere in the payload (either previously or in the future).
///
/// For formats which don't support this feature, the default implementation encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encodeWeak<T : AnyObject & Encodable>(_ object: T?, forKey key: Key) throws
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
}
/// `KeyedEncodingContainer` is a type-erased box for `KeyedEncodingContainerProtocol` types, similar to `AnyCollection` and `AnyHashable`. This is the type which consumers of the API interact with directly.
public struct KeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
associatedtype Key = K
/// Initializes `self` with the given container.
///
/// - parameter container: The container to hold.
init<Container : KeyedEncodingContainerProtocol>(_ container: Container) where Container.Key == Key
// + methods from KeyedEncodingContainerProtocol
}
/// Conformance to `KeyedDecodingContainerProtocol` indicates that a type provides a view into a `Decoder`'s storage and is used to hold the encoded properties of a `Decodable` type in a keyed manner.
///
/// Decoders should provide types conforming to `KeyedDecodingContainerProtocol` for their format.
public protocol KeyedDecodingContainerProtocol {
associatedtype Key : CodingKey
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] { get }
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool
/// Decodes a value of the given type for the given key.
///
/// A default implementation is given for these types which calls into the `decodeIfPresent` implementations below.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key or if the value is null.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool
func decode(_ type: Int.Type, forKey key: Key) throws -> Int
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64
func decode(_ type: Float.Type, forKey key: Key) throws -> Float
func decode(_ type: Double.Type, forKey key: Key) throws -> Double
func decode(_ type: String.Type, forKey key: Key) throws -> String
func decode(_ type: Data.Type, forKey key: Key) throws -> Data
func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?
func decodeIfPresent(_ type: Data.Type, forKey key: Key) throws -> Data?
func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T?
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
}
/// `KeyedDecodingContainer` is a type-erased box for `KeyedDecodingContainerProtocol` types, similar to `AnyCollection` and `AnyHashable`. This is the type which consumers of the API interact with directly.
public struct KeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
associatedtype Key = K
/// Initializes `self` with the given container.
///
/// - parameter container: The container to hold.
init<Container : KeyedDecodingContainerProtocol>(_ container: Container) where Container.Key == Key
// + methods from KeyedDecodingContainerProtocol
}
```
These `encode(_:forKey:)` and `decode(_:forKey:)` overloads give strong, static type guarantees about what is encodable (preventing accidental attempts to encode an invalid type), and provide a list of primitive types which are common to all encoders and decoders that users can rely on.
When the conditional conformance feature lands in Swift, the ability to express that "a collection of things which are `Codable` is `Codable`" will allow collections (`Array`, `Dictionary`, etc.) to be extended and fall into these overloads as well.
### Unkeyed Containers
For some types, when the source and destination of a payload can be guaranteed to agree on the payload layout and format (e.g. in cross-process communication, where both sides agree on the payload format), it may be appropriate to eschew the encoding of keys and encode sequentially, without keys. In this case, a type may choose to make use of an unkeyed container for its properties:
```swift
/// Conformance to `UnkeyedEncodingContainer` indicates that a type provides a view into an `Encoder`'s storage and is used to hold the encoded properties of an `Encodable` type sequentially, without keys.
///
/// Encoders should provide types conforming to `UnkeyedEncodingContainer` for their format.
public protocol UnkeyedEncodingContainer {
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T : Encodable>(_ value: T?) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool?) throws
mutating func encode(_ value: Int?) throws
mutating func encode(_ value: Int8?) throws
mutating func encode(_ value: Int16?) throws
mutating func encode(_ value: Int32?) throws
mutating func encode(_ value: Int64?) throws
mutating func encode(_ value: UInt?) throws
mutating func encode(_ value: UInt8?) throws
mutating func encode(_ value: UInt16?) throws
mutating func encode(_ value: UInt32?) throws
mutating func encode(_ value: UInt64?) throws
mutating func encode(_ value: Float?) throws
mutating func encode(_ value: Double?) throws
mutating func encode(_ value: String?) throws
mutating func encode(_ value: Data?) throws
/// Encodes the given object weakly.
///
/// For `Encoder`s that implement this functionality, this will only encode the given object if it is encoded unconditionally elsewhere in the payload (either previously or in the future).
///
/// For formats which don't support this feature, the default implementation encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encodeWeak<T : AnyObject & Encodable>(_ object: T?) throws
/// Encodes the elements of the given sequence.
///
/// A default implementation of these is given in an extension.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Bool
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Int
// ...
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Data
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element : Encodable
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
}
/// Conformance to `UnkeyedDecodingContainer` indicates that a type provides a view into a `Decoder`'s storage and is used to hold the encoded properties of a `Decodable` type sequentially, without keys.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for their format.
public protocol UnkeyedDecodingContainer {
/// Returns the number of elements (if known) contained within this container.
var count: Int? { get }
/// Returns whether there are no more elements left to be decoded in the container.
var isAtEnd: Bool { get }
/// Decodes a value of the given type.
///
/// A default implementation is given for these types which calls into the `decodeIfPresent` implementations below.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `CocoaError.coderValueNotFound` if the encountered encoded value is null, or of there are no more values to decode.
mutating func decode(_ type: Bool.Type) throws -> Bool
mutating func decode(_ type: Int.Type) throws -> Int
mutating func decode(_ type: Int8.Type) throws -> Int8
mutating func decode(_ type: Int16.Type) throws -> Int16
mutating func decode(_ type: Int32.Type) throws -> Int32
mutating func decode(_ type: Int64.Type) throws -> Int64
mutating func decode(_ type: UInt.Type) throws -> UInt
mutating func decode(_ type: UInt8.Type) throws -> UInt8
mutating func decode(_ type: UInt16.Type) throws -> UInt16
mutating func decode(_ type: UInt32.Type) throws -> UInt32
mutating func decode(_ type: UInt64.Type) throws -> UInt64
mutating func decode(_ type: Float.Type) throws -> Float
mutating func decode(_ type: Double.Type) throws -> Double
mutating func decode(_ type: String.Type) throws -> String
mutating func decode(_ type: Data.Type) throws -> Data
mutating func decode<T : Decodable>(_ type: T.Type) throws -> T
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool?
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int?
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8?
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16?
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32?
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64?
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt?
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8?
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16?
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32?
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64?
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float?
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double?
mutating func decodeIfPresent(_ type: String.Type) throws -> String?
mutating func decodeIfPresent(_ type: Data.Type) throws -> Data?
mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T?
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
}
```
Unkeyed encoding is fragile and generally not appropriate for archival without specific format guarantees, so keyed encoding remains the recommended approach (and is why `CodingKey` `enums` are synthesized by default unless otherwise declined).
### Single Value Containers
For other types, an array or dictionary container may not even make sense (e.g. values which are `RawRepresentable` as a single primitive value). Those types may encode and decode directly as a single value, instead of requesting an outer container:
```swift
/// A `SingleValueEncodingContainer` is a container which can support the storage and direct encoding of a single non-keyed value.
public protocol SingleValueEncodingContainer {
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encode(_ value: Bool) throws
mutating func encode(_ value: Int) throws
mutating func encode(_ value: Int8) throws
mutating func encode(_ value: Int16) throws
mutating func encode(_ value: Int32) throws
mutating func encode(_ value: Int64) throws
mutating func encode(_ value: UInt) throws
mutating func encode(_ value: UInt8) throws
mutating func encode(_ value: UInt16) throws
mutating func encode(_ value: UInt32) throws
mutating func encode(_ value: UInt64) throws
mutating func encode(_ value: Float) throws
mutating func encode(_ value: Double) throws
mutating func encode(_ value: String) throws
mutating func encode(_ value: Data) throws
}
/// A `SingleValueDecodingContainer` is a container which can support the storage and direct decoding of a single non-keyed value.
public protocol SingleValueDecodingContainer {
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value cannot be converted to the requested type.
func decode(_ type: Bool.Type) throws -> Bool
func decode(_ type: Int.Type) throws -> Int
func decode(_ type: Int8.Type) throws -> Int8
func decode(_ type: Int16.Type) throws -> Int16
func decode(_ type: Int32.Type) throws -> Int32
func decode(_ type: Int64.Type) throws -> Int64
func decode(_ type: UInt.Type) throws -> UInt
func decode(_ type: UInt8.Type) throws -> UInt8
func decode(_ type: UInt16.Type) throws -> UInt16
func decode(_ type: UInt32.Type) throws -> UInt32
func decode(_ type: UInt64.Type) throws -> UInt64
func decode(_ type: Float.Type) throws -> Float
func decode(_ type: Double.Type) throws -> Double
func decode(_ type: String.Type) throws -> String
func decode(_ type: Data.Type) throws -> Data
}
// Continuing example from before; below is automatically generated by the compiler if no customization is needed.
public enum Animal : Int, Codable {
public func encode(to encoder: Encoder) throws {
// Encode as a single value; no keys.
try encoder.singleValueContainer().encode(self.rawValue)
}
public init(from decoder: Decoder) throws {
// Decodes as a single value; no keys.
let intValue = try decoder.singleValueContainer().decode(Int.self)
if let value = Self(rawValue: intValue) {
self = value
} else {
throw CocoaError.error(.coderReadCorrupt)
}
}
}
```
In the example given above, since `Animal` uses a single value container, `[.chicken, .dog, .cow, .turkey, .dog, .chicken, .cow, .turkey, .dog]` would encode directly as `[1, 2, 4, 3, 2, 1, 4, 3, 2]`.
### Nesting
In practice, some types may also need to control how data is nested within their container, or potentially nest other containers within their container. Keyed containers allow this by returning nested containers of differing types:
```swift
// Continuing from before
public protocol KeyedEncodingContainerProtocol {
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey>
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer
}
public protocol KeyedDecodingContainerProtocol {
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey : CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey>
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer
}
```
This can be common when coding against specific external data representations:
```swift
// User type for interfacing with a specific JSON API. JSON API expects encoding as {"id": ..., "properties": {"name": ..., "timestamp": ...}}. Swift type differs from encoded type, and encoding needs to match a spec:
struct Record : Codable {
// We care only about these values from the JSON payload
let id: Int
let name: String
let timestamp: Double
// ...
private enum Keys : CodingKey {
case id
case properties
}
private enum PropertiesKeys : CodingKey {
case name
case timestamp
}
public func encode(to encoder: Encoder) throws {
let container = encoder.container(keyedBy: Keys.self, type: .dictionary)
try container.encode(id, forKey: .id)
// Set a dictionary for the "properties" key
let nested = container.nestedContainer(keyedBy: PropertiesKeys.self, forKey: .properties)
try nested.encode(name, forKey: .name)
try nested.encode(timestamp, forKey: .timestamp)
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
id = try container.decode(Int.self, forKey: .id)
let nested = try container.nestedContainer(keyedBy: PropertiesKeys.self, forKey: .properties)
name = try nested.decode(String.self, forKey: .name)
timestamp = try nested.decode(Double.self, forKey: .timestamp)
}
}
```
Unkeyed containers allow for the same types of nesting:
```swift
// Continuing from before
public protocol UnkeyedEncodingContainer {
/// Encodes a nested container keyed by the given type and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey>
/// Encodes an unkeyed encoding container and returns it.
///
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer
}
public protocol UnkeyedDecodingContainer {
/// Decodes a nested container keyed by the given type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey>
/// Decodes an unkeyed nested container.
///
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer
}
```
### Dynamic Context-Based Behavior
In some cases, types may need context in order to decide on their external representation. Some types may choose a different representation based on the encoding format that they are being read from or written to, and others based on other runtime contextual information. To facilitate this, `Encoders` and `Decoders` expose user-supplied context for consumption:
```swift
/// Represents a user-defined key for providing context for encoding and decoding.
public struct CodingUserInfoKey : RawRepresentable, Hashable {
typealias RawValue = String
let rawValue: String
init?(rawValue: String)
}
// Continuing from before:
public protocol Encoder {
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] { get }
}
public protocol Decoder {
/// Any contextual information set by the user for decoding.
var userInfo: [CodingUserInfoKey : Any] { get }
}
```
Consuming types may then support setting contextual information to inform their encoding and decoding:
```swift
public struct Person : Encodable {
public static let codingUserInfoKey = CodingUserInfoKey("com.foocorp.person.codingUserInfoKey")
public struct UserInfo {
let shouldEncodePrivateFields: Bool
// ...
}
func encode(to encoder: Encoder) throws {
if let context = encoder.userInfo[Person.codingUserInfoKey] as? Person.UserInfo {
if context.shouldEncodePrivateFields {
// Do something special.
}
}
// Fall back to default.
}
}
let encoder = ...
encoder.userInfo[Person.codingUserInfoKey] = Person.UserInfo(...)
let data = try encoder.encode(person)
```
`Encoders` and `Decoders` may choose to expose contextual information about their configuration as part of the context as well if necessary.
### Inheritance
Inheritance in this system is supported much like it is with `NSCoding` — on encoding, objects which inherit from a type that is `Encodable` encode `super` using their encoder, and pass a decoder to `super.init(from:)` on decode if they inherit from a type that is `Decodable`. With the existing `NSCoding` API, this is most often done like so, by convention:
```objc
- (void)encodeWithCoder:(NSCoder *)encoder {
[super encodeWithCoder:encoder];
// ... encode properties
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
if ((self = [super initWithCoder:decoder])) {
// ... decode properties
}
return self;
}
```
In practice, this approach means that the properties of `self` and the properties of `super` get encoded into the same container: if `self` encodes values for keys `"a"`, `"b"`, and `"c"`, and `super` encodes `"d"`, `"e"`, and `"f"`, the resulting object is encoded as `{"a": ..., "b": ..., "c": ..., "d": ..., "e": ..., "f": ...}`. This approach has two drawbacks:
1. Things which `self` encodes may overwrite `super`'s (or vice versa, depending on when `-[super encodeWithCoder:]` is called
2. `self` and `super` may not encode into different container types (e.g. `self` in a sequential fashion, and `super` in a keyed fashion)
The second point is not an issue for `NSKeyedArchiver`, since all values encode with keys (sequentially coded elements get autogenerated keys). This proposed API, however, allows for `self` and `super` to explicitly request conflicting containers (`.array` and `.dictionary`, which may not be mixed, depending on the data format).
To remedy both of these points, we adopt a new convention for inheritance-based coding — encoding `super` as a sub-object of `self`:
```swift
public class MyCodable : SomethingCodable {
public func encode(to encoder: Encoder) throws {
let container = encoder.container(keyedBy: CodingKeys.self)
// ... encode some properties
// superEncoder() gives `super` a nested container to encode into (for
// a predefined key).
try super.encode(to: container.superEncoder())
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// ... decode some properties
// Allow `super` to decode from the nested container.
try super.init(from: container.superDecoder())
}
}
```
If a shared container is desired, it is still possible to call `super.encode(to: encoder)` and `super.init(from: decoder)`, but we recommend the safer containerized option.
`superEncoder()` and `superDecoder()` are provided on containers to provide handles to nested containers for `super` to use.
```swift
// Continuing from before
public protocol KeyedEncodingContainerProtocol {
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder
}
public protocol KeyedDecodingContainerProtocol {
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the default `super` key, or if the stored value is null.
func superDecoder() throws -> Decoder
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key, or if the stored value is null.
func superDecoder(forKey key: Key) throws -> Decoder
}
public protocol UnkeyedEncodingContainer {
/// Encodes a nested container and returns an `Encoder` instance for encoding `super` into that container.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
}
public protocol UnkeyedDecodingContainer {
/// Decodes a nested container and returns a `Decoder` instance for decoding `super` from that container.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if the encountered encoded value is null, or of there are no more values to decode.
mutating func superDecoder() throws -> Decoder
}
```
### Primitive `Codable` Conformance
The encoding container types offer overloads for working with and processing the API's primitive types (`String`, `Int`, `Double`, etc.). However, for ease of implementation (both in this API and others), it can be helpful for these types to conform to `Codable` themselves. Thus, along with these overloads, we will offer `Codable` conformance on these types:
```swift
extension Bool : Codable {
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Bool.self)
}
public func encode(to encoder: Encoder) throws {
try encoder.singleValueContainer().encode( self)
}
}
// Repeat for others...
```
This conformance allows one to write functions which accept `Codable` types without needing specific overloads for the fifteen primitive types as well.
Since Swift's function overload rules prefer more specific functions over generic functions, the specific overloads are chosen where possible (e.g. `encode("Hello, world!", forKey: .greeting)` will choose `encode(_: String, forKey: Key)` over `encode<T : Codable>(_: T, forKey: Key)`).
#### Additional Extensions
Along with the primitive `Codable` conformance above, extensions on `Codable` `RawRepresentable` types whose `RawValue` is a primitive types will provide default implementations for encoding and decoding:
```swift
public extension RawRepresentable where RawValue == Bool, Self : Codable {
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw CocoaError.error(.coderReadCorrupt)
}
self = value
}
public func encode(to encoder: Encoder) throws {
try encoder.singleValueContainer().encode(self.rawValue)
}
}
// Repeat for others...
```
This allows for trivial `Codable` conformance of `enum` types (and manual `RawRepresentable` implementations) with primitive backing.
## Source compatibility
This proposal is additive — existing code will not have to change due to this API addition. This implementation can be made available in both Swift 4 and the Swift 3 compatibility mode.
## Effect on ABI stability
The addition of this API will not be an ABI-breaking change. However, this will add limitations for changes in future versions of Swift, as parts of the API will have to remain unchanged between versions of Swift (barring some additions, discussed below).
## Effect on API resilience
Much like new API added to the standard library, once added, many changes to this API will be ABI- and source-breaking changes. In particular, changes which change the types or names of methods or arguments, add required methods on protocols or classes, or remove supplied default implementations will break client behavior.
The following types may not have methods added to them without providing default implementations:
* `Encodable`
* `Decodable`
* `CodingKey`
* `Encoder`
* `KeyedEncodingContainerProtocol`
* `KeyedEncodingContainer`
* `UnkeyedEncodingContainer`
* `SingleValueEncodingContainer`
* `Decoder`
* `KeyedDecodingContainerProtocol`
* `KeyedDecodingContainer`
* `UnkeyedEncodingContainer`
* `SingleValueDecodingContainer`
Various extensions to Swift primitive types (`Bool`, `Int`, `Double`, etc.) and to `RawRepresentable` types (`where RawValue == Bool`, `== Int`, `== Double`, etc.) may also not be removed.
In general, changes to the proposed types will be restricted as described in the [library evolution document](https://github.com/apple/swift/blob/master/docs/LibraryEvolution.rst) in the Swift repository.
## Alternatives considered
The following are a few of the more notable approaches considered for the problem:
1. Leverage the existing `NSCoding` implementation by adding support for `struct` and `enum` types, either through `NSCoding` itself, or through a similar protocol.
* Although technically feasible, this can feel like a "missed opportunity" for offering something better tuned for Swift. This approach would also not offer any additional integration with `JSONSerialization` and `PropertyListSerialization`, unless JSON and plist archivers were added to offer support.
2. The following type-erased, declarative approach:
```swift
// Similar hack to AnyHashable; these wrap values which have not yet been
// encoded, or not yet decoded.
struct AnyEncodable { ... }
struct AnyDecodable { ... }
protocol CodingPrimitive {}
protocol PrimitiveCodable { /* same as above */ }
protocol OrderedCodable {
init(from: [AnyDecodable]) throws
var encoded: [AnyEncodable] { get }
}
protocol KeyedCodable {
init(from: [String: AnyDecodable]) throws
var encoded: [String: AnyEncodable] { get }
}
// Same as above
protocol OrderedEncoder { ... }
protocol OrderedDecoder { ... }
protocol KeyedEncoder { ... }
protocol KeyedDecoder { ... }
// Sample:
struct Location: OrderedCodable {
let latitude: Double
let longitude: Double
init(from array: [AnyDecodable]) throws {
guard array.count == 2 else { /* throw */ }
// These `.as()` calls perform the actual decoding, and fail by
// throwing an error.
let latitude = try array[0].as(Double.self)
let longitude = try array[1].as(Double.self)
try self.init(latitutde: latitude, longitude: longitude)
}
var encoded: [AnyEncodable] {
// With compiler support, AnyEncodable() can be automatic.
return [AnyEncodable(latitude), AnyEncodable(longitude)]
}
}
struct Farm: KeyedCodable {
let name: String
let location: Location
let animals: [Animal]
init(from dictionary: [String: AnyDecodable]) throws {
guard let name = dictionary["name"],
let location = dictionary["location"],
let animals = dictionary["animals"] else { /* throw */ }
self.name = try name.as(String.self)
self.location = try location.as(Location.self)
self.animals = try animals.asArrayOf(Animal.self)
}
var encoded: [String: AnyEncodable] {
// Similarly, AnyEncodable() should go away.
return ["name": AnyEncodable(name),
"location": AnyEncodable(location),
"animals": AnyEncodable(animals)]
}
}
```
Although the more declarative nature of this approach can be appealing, this suffers from the same problem that `JSONSerialization` currently does: as-casting. Getting an intermediate type-erased value requires casting to get a "real" value out. Doing this with an `as?`-cast requires compiler support to interject code to decode values of a given type out of their type-erased containers (similar to what happens today with `AnyHashable`). If the user requests a value of a different type than what is stored, however, the `as?`-cast will fail by returning `nil` — there is no meaningful way to report the failure. Getting the code to `throw` in cases like this requires methods on `AnyDecodable` (as shown above), but these can be confusing (when should you use `.as()` and when should you use `as?`?).
Modifications can be made to improve this:
```swift
protocol OrderedCodable {
// AnyDecodable can wrap anything, including [AnyDecodable]; unwrapping
// these can be tedious, so we want to give default implementations
// that do this.
// Default implementations for these are given in terms of the
// initializer below.
init?(from: AnyDecodable?) throws
init(from: AnyDecodable) throws
init(from: [AnyDecodable]) throws
var encoded: [AnyEncodable] { get }
}
protocol KeyedCodable {
// AnyDecodable can wrap anything, including [String: AnyDecodable];
// unwrapping these can be tedious, so we want to give default
// implementations that do this.
// Default implementations for these are given in terms of the
// initializer below.
init?(from: AnyDecodable?) throws
init(from: AnyDecodable) throws
init(from: [String: AnyDecodable]) throws
var encoded: [String: AnyEncodable] { get }
}
// Sample:
struct Location: OrderedCodable {
// ...
init(from array: [AnyDecodable]) throws {
guard array.count == 2 else { /* throw */ }
let latitude = try Double(from: array[0])
let longitude = try Double(from: array[1])
try self.init(latitude: latitude, longitude: longitude)
}
// ...
}
struct Farm: KeyedCodable {
// ...
init(from dictionary: [String: AnyDecodable]) throws {
guard let name = try String(from: dictionary["name"]),
let Location = try Location(from: dictionary["location"])
let animals = try [Animal](from: dictionary["animals"]) else {
/* throw */
}
self.name = name
self.location = location
self.animals = animals
}
// ...
}
```
By providing the new initializer methods, we can perform type casting via initialization, rather than by explicit casts. This pushes the `.as()` calls into the Swift primitives (`CodingPrimitive`s, `Array`, `Dictionary`), hiding them from end users. However, this has a different problem, namely that by offering the same type-erased initializers, `OrderedCodable` and `KeyedCodable` now conflict, and it is impossible to conform to both.
The declarative benefits here are not enough to outweigh the fact that this does not effectively remove the need to `as?`-cast.
3. The following approach, which relies on compiler code generation:
```swift
protocol Codable {
/// `EncodedType` is an intermediate representation of `Self` -- it has
/// the properties from `Self` that need to be archived and unarchived
/// (and performs that archival work), but represents at type that is
/// not yet domain-validated like `self` is.
associatedtype EncodedType: CodingRepresentation
init(from encoded: EncodedType)
var encoded: EncodedType { get }
}
protocol CodingPrimitive {}
protocol CodingRepresentation {}
protocol PrimitiveCodingRepresentation: CodingRepresentation {
/* Similar to PrimitiveCodable above */
}
protocol OrderedCodingRepresentation: CodingRepresentation {
/* Similar to OrderedCodable above */
}
protocol KeyedCodingRepresentation: CodingRepresentation {
/* Similar to KeyedCodable above */
}
// Sample:
struct Location : Codable {
let latitude: Double
let longitude: Double
// ---------------------------------------------------------------------
// Ideally, the following could be generated by the compiler (in simple
// cases; developers can choose to implement subsets of the following
// code based on where they might need to perform customizations.
init(from encoded: Encoded) throws {
latitude = encoded.latitude
longitude = encoded.longitude
}
var encoded: Encoded {
return Encoded(self)
}
// Keyed coding is the default generated by the compiler; consumers who
// want OrderedCodingRepresentation need to provide their own encoded
// type.
struct Encoded: OrderedCodingRepresentation {
let latitude: String
let longitude: String
init(_ location: Location) {
latitude = location.latitude
longitude = location.longitude
}
init(from: KeyedDecoder) throws { ... }
func encode(to: KeyedEncoder) { ... }
}
// ---------------------------------------------------------------------
}
```
This approach separates encoding and decoding into constituent steps:
1. Converting `self` into a representation fit for encoding (`EncodedType`, particularly if `EncodedType` has different properties from `Self`)
2. Converting that representation into data (`encode(into:)`)
3. Converting arbitrary bytes into validated types (`EncodedType.init(from:)`)
4. Converting validated data and types into a domain-validated value (`Self.init(from:)`).
These steps can be generated by the compiler in simple cases, with gradations up to the developer providing implementations for all of these. With this approach, it would be possible to:
1. Have a type where all code generation is left to the compiler
2. Have a type where `EncodedType` is autogenerated, but the user implements `init(from:)` (allowing for custom domain validation on decode) or `var encoded`, or both
3. Have a type where the user supplies `EncodedType`, `Self.init(from:)`, and `var encoded`, but the compiler generates `EncodedType.init(from:)` and `EncodedType.encode(into:)`. This allows the user to control what properties `EncodedType` has (or control its conformance to one of the `CodingRepresentation` types) without having to perform the actual `encode` and `decode` calls
4. Have a type where the user supplies everything, giving them full control of encoding and decoding (for implementing archive versioning and other needs)
While cases 1 and 2 save on boilerplate, types which need to be customized have significantly more boilerplate to write by hand.
4. The following approach, which delineates between keyed encoding (with `String` keys) and ordered encoding (this is the approach proposed in v1 and v2 of this proposal):
```swift
protocol PrimitiveCodable {
associatedtype Atom: CodingAtom
var atomValue: Atom { get }
init(atomValue value: Atom)
}
protocol OrderedCodable {
init(from decoder: OrderedDecoder) throws
func encode(into encoder: OrderedEncoder)
}
protocol KeyedCodable {
init(from decoder: KeyedDecoder) throws
func encode(into encoder: KeyedEncoder)
}
protocol OrderedEncoder {
func encode<Value>(_ value: Value?) where Value: CodingAtom
func encode<Value>(_ value: Value?) where Value: PrimitiveCodable
func encode<Value>(_ value: Value?) where Value: OrderedCodable
func encode<Value>(_ value: Value?) where Value: KeyedCodable
func encode<Value>(_ value: Value?) where Value: OrderedCodable & KeyedCodable
}
protocol OrderedDecoder {
var count: Int { get }
func decode<Value>(_ type: Value.Type) throws -> Value? where Value: CodingAtom
func decode<Value>(_ type: Value.Type) throws -> Value? where Value: PrimitiveCodable
func decode<Value>(_ type: Value.Type) throws -> Value? where Value: OrderedCodable
func decode<Value>(_ type: Value.Type) throws -> Value? where Value: KeyedCodable
func decode<Value>(_ type: Value.Type) throws -> Value? where Value: OrderedCodable & KeyedCodable
}
protocol KeyedEncoder {
func encode<Value>(_ value: Value?, forKey key: String) where Value: CodingPrimitive
func encode<Value>(_ value: Value?, forKey key: String) where Value: PrimitiveCodable
func encode<Value>(_ value: Value?, forKey key: String) where Value: OrderedCodable
func encode<Value>(_ value: Value?, forKey key: String) where Value: KeyedCodable
func encode<Value>(_ value: Value?, forKey key: String) where Value: OrderedCodable & KeyedCodable
}
protocol KeyedDecoder {
var allKeys: [String] { get }
func hasValue(forKey key: String) -> Bool
func decode<Value>(_ type: Value.Type, forKey key: String) throws -> Value? where Value: CodingPrimitive
func decode<Value>(_ type: Value.Type, forKey key: String) throws -> Value? where Value: PrimitiveCodable
func decode<Value>(_ type: Value.Type, forKey key: String) throws -> Value? where Value: OrderedCodable
func decode<Value>(_ type: Value.Type, forKey key: String) throws -> Value? where Value: KeyedCodable
func decode<Value>(_ type: Value.Type, forKey key: String) throws -> Value? where Value: OrderedCodable & KeyedCodable
}
```
Although this semantically separates between different types of encoding, the multiple protocols can be confusing, and it is not immediately apparent which to adopt and use. This also specifically calls out a difference between string-keyed and non-keyed coding, which is unnecessary.
5. A closure-based version of the current approach which scopes keyed encoders/decoders to call sites via closures:
```swift
protocol Encoder {
func encode(as value: Bool) throws
// ...
func with<Key>(keys type: Key.Type, _ block: (KeyedEncoder<Key>) throws -> Void) rethrows
// ...
}
internal struct Record : Codable {
let id: Int
let name: String
let timestamp: Double
// ...
public func encode(into encoder: Encoder) throws {
try encoder.with(keys: Keys.self) { keyedEncode in
try keyedEncode.encode(id, forKey: .id)
try keyedEncode.encode(.dictionary, forKey: .properties, keys: PropertiesKeys.self) { properties in
try properties.encode(name, forKey: .name)
try properties.encode(timestamp, forKey: .timestamp)
}
}
}
}
```
However, this cannot currently be applied to decoding:
```swift
public init(from decoder: Decoder) throws {
// This closure implicitly references self. Since Swift has no
// guarantees that this closure will get called exactly once, self must
// be fully initialized before this call.
//
// This would require all instance variables to be vars with default
// values.
try decoder.with(keys: Keys.self) { keyedDecoder in
id = try keyedDecoder.decode(Int.self, forKey: .id)
// ...
}
}
```
Although it is not currently possible to initialize `self` within a closure in Swift, this may be added in the future as annotations make these guarantees possible.
6. A previous approach similar to the current approach with single value encode calls available directly on `Encoder`, and a `KeyedEncoder` type instead of `KeyedEncodingContainer`:
```swift
public protocol Encoder {
func keyed<Key : CodingKey>(by: Key.Type) throws -> KeyedEncoder<Key>
func encode(as: Bool) throws
func encode(as: Int) throws
func encode(as: Int8) throws
func encode(as: Int16) throws
func encode(as: Int32) throws
// ...
}
public class KeyedEncoder<Key : CodingKey> {
// Identical to KeyedEncodingContainer
}
```
# Appendix
## `JSONSerialization` Friction and Third-Party Solutions (Motivation)
The following example usage of `JSONSerialization` is taken from the README of [SwiftyJSON](https://github.com/swiftyjson/swiftyjson), a third-party library that many developers use to interface with JSON models:
```swift
if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]],
let user = statusesArray[0]["user"] as? [String: Any],
let username = user["name"] as? String {
// Finally we got the username
}
```
SwiftyJSON attempts to elide the verbosity of casting by offering the following solution instead:
```swift
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
// Now you got your value
}
```
This friction is not necessarily a design flaw in the API, simply a truth of interfacing between JavaScript and JSON's generally untyped, unstructured contents, and Swift's strict typing. Some libraries, like SwiftyJSON, do this at the cost of type safety; others, like ObjectMapper and Argo below, maintain type safety by offering archival functionality for JSON types:
```swift
// Taken from https://github.com/Hearst-DD/ObjectMapper
class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
var bestFriend: User? // Nested User object
var friends: [User]? // Array of Users
var birthday: NSDate?
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
weight <- map["weight"]
array <- map["arr"]
dictionary <- map["dict"]
bestFriend <- map["best_friend"]
friends <- map["friends"]
birthday <- (map["birthday"], DateTransform())
}
}
struct Temperature: Mappable {
var celsius: Double?
var fahrenheit: Double?
init?(map: Map) {
}
mutating func mapping(map: Map) {
celsius <- map["celsius"]
fahrenheit <- map["fahrenheit"]
}
}
```
or the more functional
```swift
// Taken from https://github.com/thoughtbot/Argo
struct User {
let id: Int
let name: String
let email: String?
let role: Role
let companyName: String
let friends: [User]
}
extension User: Decodable {
static func decode(j: JSON) -> Decoded<User> {
return curry(User.init)
<^> j <| "id"
<*> j <| "name"
<*> j <|? "email" // Use ? for parsing optional values
<*> j <| "role" // Custom types that also conform to Decodable just work
<*> j <| ["company", "name"] // Parse nested objects
<*> j <|| "friends" // parse arrays of objects
}
}
// Wherever you receive JSON data:
let json: Any? = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
if let j: Any = json {
let user: User? = decode(j)
}
```
There are tradeoffs made here as well. ObjectMapper requires that all of your properties be optional, while Argo relies on a vast collection of custom operators and custom curried initializer functions to do its work. (While not shown in the snippet above, `User.init` code in reality is effectively implemented as `User.init(id)(name)(email)(role)(companyName)(friends)`.)
We would like to provide a solution that skirts neither type safety, nor ease-of-use and -implementation.
## Unabridged API
```swift
/// Conformance to `Encodable` indicates that a type can encode itself to an external representation.
public protocol Encodable {
/// Encodes `self` into the given encoder.
///
/// If `self` fails to encode anything, `encoder` will encode an empty keyed container in its place.
///
/// - parameter encoder: The encoder to write data to.
/// - throws: An error if any values are invalid for `encoder`'s format.
func encode(to encoder: Encoder) throws
}
/// Conformance to `Decodable` indicates that a type can decode itself from an external representation.
public protocol Decodable {
/// Initializes `self` by decoding from `decoder`.
///
/// - parameter decoder: The decoder to read data from.
/// - throws: An error if reading from the decoder fails, or if read data is corrupted or otherwise invalid.
init(from decoder: Decoder) throws
}
/// Conformance to `Codable` indicates that a type can convert itself into and out of an external representation.
public typealias Codable = Encodable & Decodable
/// Conformance to `CodingKey` indicates that a type can be used as a key for encoding and decoding.
public protocol CodingKey {
/// The string to use in a named collection (e.g. a string-keyed dictionary).
var stringValue: String { get }
/// Initializes `self` from a string.
///
/// - parameter stringValue: The string value of the desired key.
/// - returns: An instance of `Self` from the given string, or `nil` if the given string does not correspond to any instance of `Self`.
init?(stringValue: String)
/// The int to use in an indexed collection (e.g. an int-keyed dictionary).
var intValue: Int? { get }
/// Initializes `self` from an integer.
///
/// - parameter intValue: The integer value of the desired key.
/// - returns: An instance of `Self` from the given integer, or `nil` if the given integer does not correspond to any instance of `Self`.
init?(intValue: Int)
}
/// An `Encoder` is a type which can encode values into a native format for external representation.
public protocol Encoder {
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] { get }
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func container<Key : CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key>
/// Returns an encoding container appropriate for holding multiple unkeyed values.
///
/// - returns: A new empty unkeyed container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer
/// Returns an encoding container appropriate for holding a single primitive value.
///
/// - returns: A new empty single value container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer
}
/// A `Decoder` is a type which can decode values from a native format into in-memory representations.
public protocol Decoder {
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// Any contextual information set by the user for decoding.
var userInfo: [CodingUserInfoKey : Any] { get }
/// Returns the data stored in `self` as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
func container<Key : CodingKey>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key>
/// Returns the data stored in `self` as represented in a container appropriate for holding values with no keys.
///
/// - returns: An unkeyed container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
func unkeyedContainer() throws -> UnkeyedDecodingContainer
/// Returns the data stored in `self` as represented in a container appropriate for holding a single primitive value.
///
/// - returns: A single value container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a single value container.
func singleValueContainer() throws -> SingleValueDecodingContainer
}
/// Conformance to `KeyedEncodingContainerProtocol` indicates that a type provides a view into an `Encoder`'s storage and is used to hold the encoded properties of an `Encodable` type in a keyed manner.
///
/// Encoders should provide types conforming to `KeyedEncodingContainerProtocol` for their format.
public protocol KeyedEncodingContainerProtocol {
associatedtype Key : CodingKey
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T : Encodable>(_ value: T?, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool?, forKey key: Key) throws
mutating func encode(_ value: Int?, forKey key: Key) throws
mutating func encode(_ value: Int8?, forKey key: Key) throws
mutating func encode(_ value: Int16?, forKey key: Key) throws
mutating func encode(_ value: Int32?, forKey key: Key) throws
mutating func encode(_ value: Int64?, forKey key: Key) throws
mutating func encode(_ value: UInt?, forKey key: Key) throws
mutating func encode(_ value: UInt8?, forKey key: Key) throws
mutating func encode(_ value: UInt16?, forKey key: Key) throws
mutating func encode(_ value: UInt32?, forKey key: Key) throws
mutating func encode(_ value: UInt64?, forKey key: Key) throws
mutating func encode(_ value: Float?, forKey key: Key) throws
mutating func encode(_ value: Double?, forKey key: Key) throws
mutating func encode(_ value: String?, forKey key: Key) throws
mutating func encode(_ value: Data?, forKey key: Key) throws
/// Encodes the given object weakly for the given key.
///
/// For `Encoder`s that implement this functionality, this will only encode the given object and associate it with the given key if it is encoded unconditionally elsewhere in the payload (either previously or in the future).
///
/// For formats which don't support this feature, the default implementation encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encodeWeak<T : AnyObject & Encodable>(_ object: T?, forKey key: Key) throws
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey>
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder
}
/// `KeyedEncodingContainer` is a type-erased box for `KeyedEncodingContainerProtocol` types, similar to `AnyCollection` and `AnyHashable`. This is the type which consumers of the API interact with directly.
public struct KeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
associatedtype Key = K
/// Initializes `self` with the given container.
///
/// - parameter container: The container to hold.
init<Container : KeyedEncodingContainerProtocol>(_ container: Container) where Container.Key == Key
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T : Encodable>(_ value: T?, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool?, forKey key: Key) throws
mutating func encode(_ value: Int?, forKey key: Key) throws
mutating func encode(_ value: Int8?, forKey key: Key) throws
mutating func encode(_ value: Int16?, forKey key: Key) throws
mutating func encode(_ value: Int32?, forKey key: Key) throws
mutating func encode(_ value: Int64?, forKey key: Key) throws
mutating func encode(_ value: UInt?, forKey key: Key) throws
mutating func encode(_ value: UInt8?, forKey key: Key) throws
mutating func encode(_ value: UInt16?, forKey key: Key) throws
mutating func encode(_ value: UInt32?, forKey key: Key) throws
mutating func encode(_ value: UInt64?, forKey key: Key) throws
mutating func encode(_ value: Float?, forKey key: Key) throws
mutating func encode(_ value: Double?, forKey key: Key) throws
mutating func encode(_ value: String?, forKey key: Key) throws
mutating func encode(_ value: Data?, forKey key: Key) throws
/// Encodes the given object weakly for the given key.
///
/// For `Encoder`s that implement this functionality, this will only encode the given object and associate it with the given key if it is encoded unconditionally elsewhere in the payload (either previously or in the future).
///
/// For formats which don't support this feature, the default implementation encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encodeWeak<T : AnyObject & Encodable>(_ object: T?, forKey key: Key) throws
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey>
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder
}
/// Conformance to `KeyedDecodingContainerProtocol` indicates that a type provides a view into a `Decoder`'s storage and is used to hold the encoded properties of a `Decodable` type in a keyed manner.
///
/// Decoders should provide types conforming to `KeyedDecodingContainerProtocol` for their format.
public protocol KeyedDecodingContainerProtocol {
associatedtype Key : CodingKey
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] { get }
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool
/// Decodes a value of the given type for the given key.
///
/// A default implementation is given for these types which calls into the `decodeIfPresent` implementations below.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key or if the value is null.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool
func decode(_ type: Int.Type, forKey key: Key) throws -> Int
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64
func decode(_ type: Float.Type, forKey key: Key) throws -> Float
func decode(_ type: Double.Type, forKey key: Key) throws -> Double
func decode(_ type: String.Type, forKey key: Key) throws -> String
func decode(_ type: Data.Type, forKey key: Key) throws -> Data
func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?
func decodeIfPresent(_ type: Data.Type, forKey key: Key) throws -> Data?
func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T?
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey : CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey>
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the default `super` key, or if the stored value is null.
func superDecoder() throws -> Decoder
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key, or if the stored value is null.
func superDecoder(forKey key: Key) throws -> Decoder
}
/// `KeyedDecodingContainer` is a type-erased box for `KeyedDecodingContainerProtocol` types, similar to `AnyCollection` and `AnyHashable`. This is the type which consumers of the API interact with directly.
public struct KeyedDecodingContainer<K : CodingKey> : KeyedDecodingContainerProtocol {
associatedtype Key = K
/// Initializes `self` with the given container.
///
/// - parameter container: The container to hold.
init<Container : KeyedDecodingContainerProtocol>(_ container: Container) where Container.Key == Key
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
var allKeys: [Key] { get }
/// Returns whether the `Decoder` contains a value associated with the given key.
///
/// The value associated with the given key may be a null value as appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool
/// Decodes a value of the given type for the given key.
///
/// A default implementation is given for these types which calls into the `decodeIfPresent` implementations below.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key or if the value is null.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool
func decode(_ type: Int.Type, forKey key: Key) throws -> Int
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64
func decode(_ type: Float.Type, forKey key: Key) throws -> Float
func decode(_ type: Double.Type, forKey key: Key) throws -> Double
func decode(_ type: String.Type, forKey key: Key) throws -> String
func decode(_ type: Data.Type, forKey key: Key) throws -> Data
func decode<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the `Decoder` does not have an entry associated with the given key, or if the value is a null value.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?
func decodeIfPresent(_ type: Data.Type, forKey key: Key) throws -> Data?
func decodeIfPresent<T : Decodable>(_ type: T.Type, forKey key: Key) throws -> T?
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
func nestedContainer<NestedKey : CodingKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey>
/// Returns the data stored for the given key as represented in an unkeyed container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the default `super` key, or if the stored value is null.
func superDecoder() throws -> Decoder
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if `self` does not have an entry for the given key, or if the stored value is null.
func superDecoder(forKey key: Key) throws -> Decoder
}
/// Conformance to `UnkeyedEncodingContainer` indicates that a type provides a view into an `Encoder`'s storage and is used to hold the encoded properties of an `Encodable` type sequentially, without keys.
///
/// Encoders should provide types conforming to `UnkeyedEncodingContainer` for their format.
public protocol UnkeyedEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode<T : Encodable>(_ value: T?) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encode(_ value: Bool?) throws
mutating func encode(_ value: Int?) throws
mutating func encode(_ value: Int8?) throws
mutating func encode(_ value: Int16?) throws
mutating func encode(_ value: Int32?) throws
mutating func encode(_ value: Int64?) throws
mutating func encode(_ value: UInt?) throws
mutating func encode(_ value: UInt8?) throws
mutating func encode(_ value: UInt16?) throws
mutating func encode(_ value: UInt32?) throws
mutating func encode(_ value: UInt64?) throws
mutating func encode(_ value: Float?) throws
mutating func encode(_ value: Double?) throws
mutating func encode(_ value: String?) throws
mutating func encode(_ value: Data?) throws
/// Encodes the given object weakly.
///
/// For `Encoder`s that implement this functionality, this will only encode the given object if it is encoded unconditionally elsewhere in the payload (either previously or in the future).
///
/// For formats which don't support this feature, the default implementation encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
mutating func encodeWeak<T : AnyObject & Encodable>(_ object: T?) throws
/// Encodes the elements of the given sequence.
///
/// A default implementation of these is given in an extension.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Bool
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Int
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Int8
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Int16
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Int32
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Int64
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == UInt
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == UInt8
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == UInt16
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == UInt32
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == UInt64
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Float
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Double
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == String
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element == Data
mutating func encode<Sequence : Swift.Sequence>(contentsOf sequence: Sequence) throws where Sequence.Iterator.Element : Encodable
/// Encodes a nested container keyed by the given type and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey>
/// Encodes an unkeyed encoding container and returns it.
///
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer
/// Encodes a nested container and returns an `Encoder` instance for encoding `super` into that container.
///
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
}
/// Conformance to `UnkeyedDecodingContainer` indicates that a type provides a view into a `Decoder`'s storage and is used to hold the encoded properties of a `Decodable` type sequentially, without keys.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for their format.
public protocol UnkeyedDecodingContainer {
/// The path of coding keys taken to get to this point in decoding.
/// A `nil` value indicates an unkeyed container.
var codingPath: [CodingKey?] { get }
/// Returns the number of elements (if known) contained within this container.
var count: Int? { get }
/// Returns whether there are no more elements left to be decoded in the container.
var isAtEnd: Bool { get }
/// Decodes a value of the given type.
///
/// A default implementation is given for these types which calls into the `decodeIfPresent` implementations below.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
/// - throws: `CocoaError.coderValueNotFound` if the encountered encoded value is null, or of there are no more values to decode.
mutating func decode(_ type: Bool.Type) throws -> Bool
mutating func decode(_ type: Int.Type) throws -> Int
mutating func decode(_ type: Int8.Type) throws -> Int8
mutating func decode(_ type: Int16.Type) throws -> Int16
mutating func decode(_ type: Int32.Type) throws -> Int32
mutating func decode(_ type: Int64.Type) throws -> Int64
mutating func decode(_ type: UInt.Type) throws -> UInt
mutating func decode(_ type: UInt8.Type) throws -> UInt8
mutating func decode(_ type: UInt16.Type) throws -> UInt16
mutating func decode(_ type: UInt32.Type) throws -> UInt32
mutating func decode(_ type: UInt64.Type) throws -> UInt64
mutating func decode(_ type: Float.Type) throws -> Float
mutating func decode(_ type: Double.Type) throws -> Double
mutating func decode(_ type: String.Type) throws -> String
mutating func decode(_ type: Data.Type) throws -> Data
mutating func decode<T : Decodable>(_ type: T.Type) throws -> T
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to decode, or if the value is null. The difference between these states can be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value is a null value, or if there are no more elements to decode.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool?
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int?
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8?
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16?
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32?
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64?
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt?
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8?
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16?
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32?
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64?
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float?
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double?
mutating func decodeIfPresent(_ type: String.Type) throws -> String?
mutating func decodeIfPresent(_ type: Data.Type) throws -> Data?
mutating func decodeIfPresent<T : Decodable>(_ type: T.Type) throws -> T?
/// Decodes a nested container keyed by the given type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not a keyed container.
mutating func nestedContainer<NestedKey : CodingKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey>
/// Decodes an unkeyed nested container.
///
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered stored value is not an unkeyed container.
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer
/// Decodes a nested container and returns a `Decoder` instance for decoding `super` from that container.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `CocoaError.coderValueNotFound` if the encountered encoded value is null, or of there are no more values to decode.
mutating func superDecoder() throws -> Decoder
}
/// A `SingleValueEncodingContainer` is a container which can support the storage and direct encoding of a single non-keyed value.
public protocol SingleValueEncodingContainer {
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `CocoaError.coderInvalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encode(_ value: Bool) throws
mutating func encode(_ value: Int) throws
mutating func encode(_ value: Int8) throws
mutating func encode(_ value: Int16) throws
mutating func encode(_ value: Int32) throws
mutating func encode(_ value: Int64) throws
mutating func encode(_ value: UInt) throws
mutating func encode(_ value: UInt8) throws
mutating func encode(_ value: UInt16) throws
mutating func encode(_ value: UInt32) throws
mutating func encode(_ value: UInt64) throws
mutating func encode(_ value: Float) throws
mutating func encode(_ value: Double) throws
mutating func encode(_ value: String) throws
mutating func encode(_ value: Data) throws
}
/// A `SingleValueDecodingContainer` is a container which can support the storage and direct decoding of a single non-keyed value.
public protocol SingleValueDecodingContainer {
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `CocoaError.coderTypeMismatch` if the encountered encoded value cannot be converted to the requested type.
func decode(_ type: Bool.Type) throws -> Bool
func decode(_ type: Int.Type) throws -> Int
func decode(_ type: Int8.Type) throws -> Int8
func decode(_ type: Int16.Type) throws -> Int16
func decode(_ type: Int32.Type) throws -> Int32
func decode(_ type: Int64.Type) throws -> Int64
func decode(_ type: UInt.Type) throws -> UInt
func decode(_ type: UInt8.Type) throws -> UInt8
func decode(_ type: UInt16.Type) throws -> UInt16
func decode(_ type: UInt32.Type) throws -> UInt32
func decode(_ type: UInt64.Type) throws -> UInt64
func decode(_ type: Float.Type) throws -> Float
func decode(_ type: Double.Type) throws -> Double
func decode(_ type: String.Type) throws -> String
func decode(_ type: Data.Type) throws -> Data
}
/// Represents a user-defined key for providing context for encoding and decoding.
public struct CodingUserInfoKey : RawRepresentable, Hashable {
typealias RawValue = String
let rawValue: String
init?(rawValue: String)
init(_ value: String)
}
// Repeat for all primitive types...
extension Bool : Codable {
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Bool.self)
}
public func encode(to encoder: Encoder) throws {
try encoder.singleValueContainer().encode( self)
}
}
// Repeat for all primitive types...
public extension RawRepresentable where RawValue == Bool, Self : Codable {
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw CocoaError.error(.coderReadCorrupt)
}
self = value
}
public func encode(to encoder: Encoder) throws {
try encoder.singleValueContainer().encode(self.rawValue)
}
}
```
----------
[Previous](@previous) | [Next](@next)
*/
|
mit
|
4f6739ebd9114461f9ed8dc8859c1ee0
| 51.502686 | 808 | 0.702467 | 4.585083 | false | false | false | false |
nuan-nuan/Persei
|
Persei/Source/Menu/MenuView.swift
|
2
|
4209
|
// For License please refer to LICENSE file in the root of Persei project
import Foundation
import UIKit
private let CellIdentifier = "MenuCell"
private let DefaultContentHeight: CGFloat = 112.0
public class MenuView: StickyHeaderView {
// MARK: - Init
override func commonInit() {
super.commonInit()
if backgroundColor == nil {
backgroundColor = UIColor(red: 51 / 255, green: 51 / 255, blue: 76 / 255, alpha: 1)
}
contentHeight = DefaultContentHeight
updateContentLayout()
}
// MARK: - FlowLayout
private lazy var collectionLayout: UICollectionViewFlowLayout = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
return layout
}()
// MARK: - CollectionView
private lazy var collectionView: UICollectionView = { [unowned self] in
let view = UICollectionView(frame: CGRectZero, collectionViewLayout: self.collectionLayout)
view.clipsToBounds = false
view.backgroundColor = UIColor.clearColor()
view.showsHorizontalScrollIndicator = false
view.registerClass(MenuCell.self, forCellWithReuseIdentifier: CellIdentifier)
view.delegate = self
view.dataSource = self
self.contentView = view
return view
}()
// MARK: - Delegate
@IBOutlet
public weak var delegate: MenuViewDelegate?
// TODO: remove explicit type declaration when compiler error will be fixed
public var items: [MenuItem] = [] {
didSet {
collectionView.reloadData()
selectedIndex = items.count > 0 ? 0 : nil
}
}
public var selectedIndex: Int? = 0 {
didSet {
var indexPath: NSIndexPath?
if let index = self.selectedIndex {
indexPath = NSIndexPath(forItem: index, inSection: 0)
}
self.collectionView.selectItemAtIndexPath(indexPath,
animated: self.revealed,
scrollPosition: .CenteredHorizontally
)
}
}
// MARK: - ContentHeight & Layout
public override var contentHeight: CGFloat {
didSet {
updateContentLayout()
}
}
private func updateContentLayout() {
let inset = ceil(contentHeight / 6.0)
let spacing = floor(inset / 2.0)
collectionLayout.minimumLineSpacing = spacing
collectionLayout.minimumInteritemSpacing = spacing
collectionView.contentInset = UIEdgeInsets(top: 0.0, left: inset, bottom: 0.0, right: inset)
collectionLayout.itemSize = CGSize(width: contentHeight - inset * 2, height: contentHeight - inset * 2)
}
}
extension MenuView {
public func frameOfItemAtIndex(index: Int) -> CGRect {
let indexPath = NSIndexPath(forItem: index, inSection: 0)
let layoutAttributes = collectionLayout.layoutAttributesForItemAtIndexPath(indexPath)!
return self.convertRect(layoutAttributes.frame, fromView: collectionLayout.collectionView)
}
}
extension MenuView: UICollectionViewDataSource {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
CellIdentifier,
forIndexPath: indexPath
) as? MenuCell
// compatibility with Swift 1.1 & 1.2
cell?.object = items[indexPath.item]
return cell!
}
}
extension MenuView: UICollectionViewDelegate {
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIndex = indexPath.item
delegate?.menu(self, didSelectItemAtIndex: selectedIndex!)
UIView.animateWithDuration(0.2, delay: 0.4, options: [], animations: {
self.revealed = false
}, completion: nil)
}
}
|
mit
|
f7378ca66f01587caf1cf53600b7d9e7
| 31.882813 | 137 | 0.646472 | 5.627005 | false | false | false | false |
Pretz/SwiftGraphics
|
SwiftGraphics_OSX_Playground/Will Deprecate/Bitmap.swift
|
3
|
1087
|
//
// Bitmap.swift
// SwiftGraphics
//
// Created by Jonathan Wight on 1/17/15.
// Copyright (c) 2015 schwa.io. All rights reserved.
//
import SwiftGraphics
public struct Bitmap {
public let size: UIntSize
public let bitsPerComponent: UInt
public let bitsPerPixel: UInt
public let bytesPerRow: UInt
public let ptr: UnsafeMutablePointer<Void>
public var bytesPerPixel: UInt {
return bitsPerPixel / 8
}
public init(size: UIntSize, bitsPerComponent: UInt, bitsPerPixel: UInt, bytesPerRow: UInt, ptr: UnsafeMutablePointer <Void>) {
self.size = size
self.bitsPerComponent = bitsPerComponent
self.bitsPerPixel = bitsPerPixel
self.bytesPerRow = bytesPerRow
self.ptr = ptr
}
public subscript (index: UIntPoint) -> UInt32 {
assert(index.x < size.width)
assert(index.y < size.height)
let offset = index.y * bytesPerRow + index.x * bytesPerPixel
let offsetPointer = ptr.advancedBy(Int(offset))
return UnsafeMutablePointer <UInt32> (offsetPointer).memory
}
}
|
bsd-2-clause
|
fb48d0317b5250e6f4bb797c3744bf71
| 29.194444 | 130 | 0.673413 | 4.473251 | false | false | false | false |
SomeHero/iShopAwayAPIManager
|
IShopAwayApiManager/Classes/models/User.swift
|
1
|
2151
|
//
// User.swift
// User
//
// Created by James Rhodes on 5/16/16.
// Copyright © 2016 James Rhodes. All rights reserved.
//
import Foundation
import ObjectMapper
public class User: Mappable {
public static var sharedUser: User?
public var id: String!
public var firstName: String!
public var lastName: String!
public var emailAddress: String!
public var avatarUrl: String!
public var paymentMethods: [PaymentMethod] = []
public var shippingAddresses: [Address] = []
public init(firstName: String, lastName: String, emailAddress: String) {
self.firstName = firstName
self.lastName = lastName
self.emailAddress = emailAddress
}
public required init?(_ map: Map){
mapping(map)
}
public func mapping(map: Map) {
id <- map["_id"]
firstName <- map["first_name"]
lastName <- map["last_name"]
emailAddress <- map["email_address"]
avatarUrl <- map["avatar_url"]
paymentMethods <- map["payment_methods"]
shippingAddresses <- map["shipping_addresses"]
}
public func persistUser() {
guard let user = User.sharedUser else {
return
}
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setValuesForKeysWithDictionary([
"id": user.id!,
"first_name": user.firstName,
"last_name": user.lastName,
"email_address": user.emailAddress
])
userDefaults.synchronize()
}
public static func getPersistedUser() -> User? {
let userDefaults = NSUserDefaults.standardUserDefaults()
guard let id = userDefaults.stringForKey("id") else {
return nil
}
let firstName = userDefaults.stringForKey("first_name")!
let lastName = userDefaults.stringForKey("last_name")!
let emailAddress = userDefaults.stringForKey("email_address")!
let user = User(firstName: firstName, lastName: lastName, emailAddress: emailAddress)
user.id = id
return user
}
}
|
mit
|
461edec37f974a86400edf67873a3fdf
| 28.875 | 93 | 0.607907 | 4.965358 | false | false | false | false |
NUKisZ/MyTools
|
MyTools/MyTools/Class/ThirdVC/BKBK/NUKController/HomeViewController.swift
|
1
|
6442
|
//
// HomeViewController.swift
// NUK
//
// Created by NUK on 16/8/13.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class BKHomeViewController: BaseViewController,ZKDownloaderDelegate,UICollectionViewDelegate,UICollectionViewDataSource {
fileprivate var collView:UICollectionView?
fileprivate lazy var dataArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
self.createCollView()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "清除缓存", style: UIBarButtonItemStyle.done, target: self, action: #selector(clearCache))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "刷新", style: .done, target: self, action: #selector(reloadNewDataAction))
downloaderData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//设置信号栏状态颜色
//UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
}
@objc private func reloadNewDataAction(){
downloaderData()
}
@objc private func clearCache(){
let alert = UIAlertController(title: "提示", message: "缓存大小为\(CacheTool.cacheSize)", preferredStyle: .alert)
let actionCancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let action = UIAlertAction(title: "确定", style: .default) { (alert) in
var message = "清除成功"
if CacheTool.clearCache() {
message = "清除失败"
}
let alert = UIAlertController(title: "提示", message: message , preferredStyle: .alert)
let action = UIAlertAction(title: "确定", style: .cancel, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
alert.addAction(action)
alert.addAction(actionCancel)
self.present(alert, animated: true, completion: nil)
}
private func downloaderData() {
let urlString = "http://picaman.picacomic.com/api/categories"
let download = ZKDownloader()
download.getWithUrl(urlString)
download.delegate = self
}
private func createCollView(){
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 2
layout.minimumLineSpacing = 2
layout.itemSize = CGSize(width: 80, height: 80)
layout.sectionInset = UIEdgeInsetsMake(2, 2, 2, 2)
self.automaticallyAdjustsScrollViewInsets = false
self.collView = UICollectionView(frame: CGRect(x: 0, y: 64, width: kScreenWidth, height: kScreenHeight-64), collectionViewLayout: layout)
self.collView?.delegate = self
self.collView?.dataSource = self
self.collView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
self.collView?.backgroundColor = UIColor.white
self.view.addSubview(self.collView!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension BKHomeViewController{
func downloader(_ download: ZKDownloader, didFailWithError error: NSError) {
collView?.headerView?.endRefreshing()
ZKTools.showAlert(error.localizedDescription, onViewController: self)
}
func downloader(_ download: ZKDownloader, didFinishWithData data: Data?) {
let jsonData = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
if (jsonData as AnyObject).isKind(of: NSArray.self){
let array = jsonData as! NSArray
dataArray.removeAllObjects()
for arrayDict in array{
let dict = arrayDict as! Dictionary<String,AnyObject>
let model = HomePageModel()
model.setValuesForKeys(dict)
self.dataArray.add(model)
}
DispatchQueue.main.async(execute: {
[weak self] in
self?.collView?.reloadData()
})
}
}
}
extension BKHomeViewController{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray.count
}
@objc(collectionView:cellForItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let coll = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
for oldSubView in coll.contentView.subviews{
oldSubView.removeFromSuperview()
}
let model = self.dataArray[(indexPath as NSIndexPath).item]as! HomePageModel
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
let urlString = URL(string: model.cover_image!)
imageView.kf.setImage(with: urlString)
let label = UILabel(frame: CGRect(x: 0,y: 60,width: 80,height: 20))
label.text = "\((model.all_comics)!)"
label.textAlignment = .center
label.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
imageView.addSubview(label)
coll.contentView.addSubview(imageView)
return coll
}
@objc(collectionView:didSelectItemAtIndexPath:) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let groupListCtrl = GroupListViewController()
let model = self.dataArray[(indexPath as NSIndexPath).item] as! HomePageModel
groupListCtrl.id = "\((model.id)!)"
self.navigationController?.pushViewController(groupListCtrl, animated: true)
}
}
|
mit
|
2235d451527c4c6f7c2f4f44e50297c2
| 38.76875 | 167 | 0.65598 | 5.010236 | false | false | false | false |
ChernyshenkoTaras/CTValidationTextField
|
CTValidationTextField/Example/CTValidationTextField/TableViewController.swift
|
1
|
1393
|
//
// ViewController.swift
// CTValidationTextField
//
// Created by Taras Chernyshenko on 03/04/2017.
// Copyright (c) 2017 Taras Chernyshenko. All rights reserved.
//
import UIKit
import CTValidationTextField
class TableViewController: UITableViewController {
@IBOutlet private weak var nameTextField: CTValidationTextField?
@IBOutlet private weak var emailTextField: CTValidationTextField?
@IBOutlet private weak var phoneTextField: CTValidationTextField?
@IBOutlet private weak var addressTextField: CTValidationTextField?
override func viewDidLoad() {
super.viewDidLoad()
let numbersRule = NumbersRule(mode: .canOverlap)
let lettersRule = LetterRule(mode: .canOverlap)
let symbolsRule = SymbolsRule(symbols: [" ", "-", "'"], mode: .canOverlap)
let emailRule = EmailRule()
self.nameTextField?.validationRules = [lettersRule, numbersRule, symbolsRule]
self.emailTextField?.validationRules = [emailRule, MinLengthRule(min: 7)]
self.phoneTextField?.validationRules = [numbersRule, MinLengthRule(min: 8),
SymbolsRule(symbols: ["+"], mode: .canOverlap)]
self.addressTextField?.validationRules = [
lettersRule, numbersRule,
SymbolsRule(symbols: ["#", "(", ")", "\\", ".", ",", "-", " "],
mode: .canOverlap)
]
}
}
|
mit
|
f1900d4d95cb5bb0f3f5e25da5a6b59b
| 36.648649 | 85 | 0.664034 | 4.786942 | false | false | false | false |
EvansPie/EPDeckView
|
Pod/Classes/EPDeckView.swift
|
1
|
19007
|
//
// CardView.swift
// EPDeckView
//
// Created by Evangelos Pittas on 24/02/16.
// Copyright © 2016 EP. All rights reserved.
//
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import UIKit
// MARK: - DECKVIEW DATA SOURCE
//_______________________________________________________________________________________________________________
// This protocol provides the two basic (and required) functions to create the DeckView. It works exactly as a
// UITableView.
//
// numberOfCardsInDeckView(_:) returns the number of cards that the DeckView will hold.
//
// deckView(_:, cardViewAtIndex:) returns the view (that must be a subclass of the CardView) for each index.
//
@objc public protocol EPDeckViewDataSource : NSObjectProtocol {
func numberOfCardsInDeckView(deckView: EPDeckView) -> Int
func deckView(deckView: EPDeckView, cardViewAtIndex index: Int) -> EPCardView
}
// MARK: - DECKVIEW DELEGATE
//_______________________________________________________________________________________________________________
// This protocol consists of five optional functions to help with the cards' movement.
//
@objc public protocol EPDeckViewDelegate : NSObjectProtocol {
// The function below is called when a card moves outside of the screen, and also specifies if the card has
// moved left or right.
optional func deckView(deckView: EPDeckView, cardAtIndex index: Int, movedToDirection direction: CardViewDirection)
// The function below returns the button that implements the functionality to move the card to the right.
// Each card can have its' own button.
optional func deckView(deckView: EPDeckView, rightButtonForCardAtIndex index: Int) -> UIButton?
// The function below returns the button that implements the functionality to move the card to the left.
// Each card can have its' own button.
optional func deckView(deckView: EPDeckView, leftButtonForCardAtIndex index: Int) -> UIButton?
// The function below is called when the button with the move right functionality is tapped.
optional func deckView(deckView: EPDeckView, didTapRightButtonAtIndex index: Int)
// The function below is called when the button with the move left functionality is tapped.
optional func deckView(deckView: EPDeckView, didTapLeftButtonAtIndex index: Int)
}
// MARK: - DECKVIEW
//_______________________________________________________________________________________________________________
//
public class EPDeckView: UIView {
// MARK: Properties
// The animation manager holds the vars for the card dragging and deck view animations.
public var deckViewAnimationManager: EPDeckViewAnimationManager! {
didSet {
self.allowDeckViewAnimationManagerModify = false
}
}
private var allowDeckViewAnimationManagerModify: Bool = true
// Holds the index of the top card on the deck view.
private(set) var topCardIndex: Int = 0 {
didSet {
for cardView in self.deck {
cardView.userInteractionEnabled = false
}
if self.topCardIndex < self.deck.count {
self.deck[self.topCardIndex].userInteractionEnabled = true
}
}
}
// Calculated cards' tranformations (angle, scale, alpha & center position) are stored in these arrays.
private(set) var deck: [EPCardView] = []
private(set) var cardAnglesDegrees: [CGFloat] = []
private(set) var cardScalePercentages: [CGFloat] = []
private(set) var cardAlphas: [CGFloat] = []
private(set) var transformedCardCenters: [CGPoint] = []
// The delegate & data source.
public var delegate: EPDeckViewDelegate?
public var dataSource: EPDeckViewDataSource?
// MARK: - DeckView Initialization
public required override init(frame: CGRect) {
super.init(frame: frame)
self.addObserver(self, forKeyPath: "center", options: NSKeyValueObservingOptions.Old, context: nil)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.addObserver(self, forKeyPath: "center", options: NSKeyValueObservingOptions.Old, context: nil)
}
deinit {
self.removeObserver(self, forKeyPath: "frame")
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath != nil && object != nil {
if keyPath! == "center" && self == object as? EPDeckView {
if self.allowDeckViewAnimationManagerModify == true {
// Initialize the default DeckViewAnimationManager. It may be replaced afterwards.
self.deckViewAnimationManager = EPDeckViewAnimationManager(frame: self.frame)
}
}
}
}
// MARK: - CardView Functions
// The function reloadCards clears the DeckView and reloads the cards. It works as UITableView's reload data.
public func reloadCards() {
for card in self.deck {
card.removeFromSuperview()
}
if self.deckViewAnimationManager == nil {
self.deckViewAnimationManager = EPDeckViewAnimationManager(frame: self.frame)
}
self.deck = []
for var i=0; i<self.dataSource?.numberOfCardsInDeckView(self); i++ {
let cardView: EPCardView = self.dataSource!.deckView(self, cardViewAtIndex: i)
cardView.center = self.deckViewAnimationManager.deckCenter
cardView.delegate = self
if let rightButton: UIButton = self.delegate?.deckView?(self, rightButtonForCardAtIndex: i) {
rightButton.tag = i
rightButton.addTarget(self, action: Selector("rightButtonTapped:"), forControlEvents: .TouchUpInside)
}
if let leftButton: UIButton = self.delegate?.deckView?(self, leftButtonForCardAtIndex: i) {
leftButton.tag = i
leftButton.addTarget(self, action: Selector("leftButtonTapped:"), forControlEvents: .TouchUpInside)
}
self.deck.append(cardView)
}
self.applyCardViewsInitialTransformation()
for var i=self.deck.count-1; i>=0; i-- {
let cardView: EPCardView = self.deck[i]
cardView.alpha = self.cardAlphas[i]
self.addSubview(cardView)
}
self.topCardIndex = 0
}
// The function moveCardAtIndex(_:, direction:) moves the specified card of the index to the direction given
// (i.e. left or right).
public func moveCardAtIndex(index: Int, toDirection direction: CardViewDirection) {
let cardView: EPCardView = self.deck[index]
switch direction {
case .Right:
cardView.moveToRight()
break
case .Left:
cardView.moveToLeft()
break
}
}
// The function moveTopCardToDirection(_:) moves the top card of the deck to the direction given (i.e. left
// or right).
public func moveTopCardToDirection(direction: CardViewDirection) {
let cardView: EPCardView = self.deck[self.topCardIndex]
switch direction {
case .Right:
cardView.moveToRight()
break
case .Left:
cardView.moveToLeft()
break
}
}
// The function moveMovedCardBackToDeckViewTop() moves the the last card that left the deck, back to the top
// of the DeckView.
public func bringBackLastCardThrown() {
if self.topCardIndex > 0 {
if let lastMovedCardView: EPCardView = self.deck[self.topCardIndex-1] {
lastMovedCardView.moveToCenter()
}
}
}
// The selector function of the delegate's right movement button that is returned by:
// deckView(_:, rightButtonForIndex:)
@objc private func rightButtonTapped(sender: UIButton) {
self.moveCardAtIndex(sender.tag, toDirection: .Right)
self.delegate?.deckView?(self, didTapRightButtonAtIndex: sender.tag)
}
// The selector function of the delegate's left movement button that is returned by:
// deckView(_:, leftButtonForIndex:)
@objc private func leftButtonTapped(sender: UIButton) {
self.moveCardAtIndex(sender.tag, toDirection: .Left)
self.delegate?.deckView?(self, didTapLeftButtonAtIndex: sender.tag)
}
// MARK: - Initial CardViews Transformations
// Calculate the angle, scale & alpha for each card and apply its transformation.
private func applyCardViewsInitialTransformation() {
self.calculateCardAngles()
self.calculateCardScales()
self.calculateCardAlphas()
self.transformCards()
NSNotificationCenter.defaultCenter().postNotificationName("kCardViewsTransformationCompleted", object: nil, userInfo: nil)
}
// Calculate each card's angle (based on the DeckViewAnimationManager) and store them in an array.
private func calculateCardAngles() {
var tmpComputedCardAngles: [CGFloat] = []
for (i, _) in self.deck.enumerate() {
let tmpCardAngle = CGFloat(i) * self.deckViewAnimationManager.deckCardAngleDelta
tmpComputedCardAngles.append(tmpCardAngle)
}
self.cardAnglesDegrees = tmpComputedCardAngles
}
// Calculate each card's scale (based on the DeckViewAnimationManager) and store them in an array.
private func calculateCardScales() {
var tmpComputedCardScalePercentages: [CGFloat] = []
for (i, _) in self.deck.enumerate() {
var tmpCardScale = 1 - CGFloat(i) * self.deckViewAnimationManager.deckViewCardScaleDelta
if tmpCardScale > 1.0 {
tmpCardScale = 1.0
}
if tmpCardScale < 0 {
tmpCardScale = 0
}
tmpComputedCardScalePercentages.append(tmpCardScale)
}
self.cardScalePercentages = tmpComputedCardScalePercentages
}
// Calculate each card's transparency (based on the DeckViewAnimationManager) and store them in an array.
private func calculateCardAlphas() {
var tmpComputedCardAlphas: [CGFloat] = []
for (i, _) in self.deck.enumerate() {
var tmpCardAlpha = 1 - CGFloat(i) * self.deckViewAnimationManager.deckCardAlphaDelta
if tmpCardAlpha > 1.0 {
tmpCardAlpha = 1.0
}
if tmpCardAlpha < 0 {
tmpCardAlpha = 0
}
if i >= self.deckViewAnimationManager.deckMaxVisibleCards {
tmpCardAlpha = 0
}
tmpComputedCardAlphas.append(tmpCardAlpha)
}
if tmpComputedCardAlphas.count > 0 {
tmpComputedCardAlphas[tmpComputedCardAlphas.count - 1] = 0.0
}
self.cardAlphas = tmpComputedCardAlphas
}
// Apply each card's transformation based on angle, scale and anchor point and store their new centers
// in the property array.
private func transformCards() {
self.transformedCardCenters = []
for (i, cardView) in self.deck.enumerate() {
cardView.transform = self.getCardViewTransformForIndex(i)
cardView.anchorTo(self.deckViewAnimationManager.deckAnchor)
self.transformedCardCenters.append(cardView.center)
}
}
// Store each card's transformation.
private func getCardViewTransformForIndex(index: Int) -> CGAffineTransform {
return CGAffineTransformScale(
CGAffineTransformMakeRotation(self.cardAnglesDegrees[index].toRad()),
self.cardScalePercentages[index],
self.cardScalePercentages[index])
}
}
// MARK: - CARDVIEW DELEGATE
extension EPDeckView: EPCardViewDelegate {
// The card is being dragged, so move the rest of the cards accordingly.
func cardView(cardView: EPCardView, beingDragged gestureRecognizer: UIPanGestureRecognizer) {
let xFromCenter:CGFloat = gestureRecognizer.translationInView(cardView).x
let maxMovement: CGFloat = self.bounds.width / 2.0
let transformPercentage: CGFloat = min(fabs(xFromCenter) / maxMovement, 1.0) // 0.0 ~> 1.0
switch gestureRecognizer.state {
case UIGestureRecognizerState.Changed:
let cardViewsToTransform: [EPCardView] = Array(self.deck.suffixFrom(self.topCardIndex))
for (i, cardViewToTransform) in cardViewsToTransform.enumerate() {
if i == 0 {
continue
}
let rotationAngle: CGFloat = (self.cardAnglesDegrees[i-1] - self.deckViewAnimationManager.deckCardAngleDelta * transformPercentage + self.deckViewAnimationManager.deckCardAngleDelta).toRad()
let rotationAngleTransform: CGAffineTransform = CGAffineTransformMakeRotation(rotationAngle)
let scale: CGFloat = self.cardScalePercentages[i] + self.deckViewAnimationManager.deckViewCardScaleDelta * transformPercentage
let scaleTransform: CGAffineTransform = CGAffineTransformScale(rotationAngleTransform, scale, scale)
let moveX: CGFloat = -transformPercentage * (self.transformedCardCenters[i].x - self.transformedCardCenters[i-1].x)
let moveY: CGFloat = -transformPercentage * (self.transformedCardCenters[i].y - self.transformedCardCenters[i-1].y)
let moveTransform: CGAffineTransform = CGAffineTransformMakeTranslation(moveX, moveY)
cardViewToTransform.transform = CGAffineTransformConcat(moveTransform, scaleTransform)
cardViewToTransform.alpha = self.cardAlphas[i] + ((self.cardAlphas[i-1] - self.cardAlphas[i]) * transformPercentage)
}
break
default:
break
}
}
// The card has stopped being dragged, so move the rest of the cards accordingly.
func cardView(cardView: EPCardView, afterSwipeMovedTo cardViewEndPoint: CardViewEndPoint) {
if cardViewEndPoint == .Center {
let cardViewsToTransform: [EPCardView] = Array(self.deck.suffixFrom(self.topCardIndex))
for (i, cardViewToTransform) in cardViewsToTransform.enumerate() {
UIView.animateWithDuration(self.deckViewAnimationManager.deckAnimationDuration,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
let rotationAngle: CGFloat = self.cardAnglesDegrees[i].toRad()
let rotationAngleTransform: CGAffineTransform = CGAffineTransformMakeRotation(rotationAngle)
let scale: CGFloat = self.cardScalePercentages[i]
let scaleTransform: CGAffineTransform = CGAffineTransformScale(rotationAngleTransform, scale, scale)
cardViewToTransform.center = self.transformedCardCenters[i]
cardViewToTransform.transform = scaleTransform
cardViewToTransform.alpha = self.cardAlphas[i]
},
completion: nil
)
}
}
}
// The card moves out of the screen (left or right).
func cardView(cardView: EPCardView, movingToDirection direction: CardViewDirection) {
let cardViewsToTransform: [EPCardView] = Array(self.deck.suffixFrom(self.topCardIndex))
for (i, cardViewToTransform) in cardViewsToTransform.enumerate() {
if i == 0 {
continue
}
UIView.animateWithDuration(self.deckViewAnimationManager.deckAnimationDuration,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
let rotationAngle: CGFloat = self.cardAnglesDegrees[i-1].toRad()
let rotationAngleTransform: CGAffineTransform = CGAffineTransformMakeRotation(rotationAngle)
let scale: CGFloat = self.cardScalePercentages[i-1]
let scaleTransform: CGAffineTransform = CGAffineTransformScale(rotationAngleTransform, scale, scale)
cardViewToTransform.center = self.transformedCardCenters[i-1]
cardViewToTransform.transform = scaleTransform
cardViewToTransform.alpha = self.cardAlphas[i-1]
},
completion: nil
)
}
self.topCardIndex++
self.delegate?.deckView?(self, cardAtIndex: self.topCardIndex, movedToDirection: direction)
}
func cardView(cardView: EPCardView, cardViewMovedTo cardViewEndPoint: CardViewEndPoint) {
let cardViewsToTransform: [EPCardView] = Array(self.deck.suffixFrom(self.topCardIndex))
for (i, cardViewToTransform) in cardViewsToTransform.enumerate() {
UIView.animateWithDuration(self.deckViewAnimationManager.deckAnimationDuration,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
let rotationAngle: CGFloat = self.cardAnglesDegrees[i+1].toRad()
let rotationAngleTransform: CGAffineTransform = CGAffineTransformMakeRotation(rotationAngle)
let scale: CGFloat = self.cardScalePercentages[i+1]
let scaleTransform: CGAffineTransform = CGAffineTransformScale(rotationAngleTransform, scale, scale)
cardViewToTransform.center = self.transformedCardCenters[i+1]
cardViewToTransform.transform = scaleTransform
cardViewToTransform.alpha = self.cardAlphas[i+1]
},
completion: nil
)
}
self.topCardIndex--
}
}
|
mit
|
3fb677a53ebb62d95639994a907b0afe
| 37.787755 | 206 | 0.604809 | 5.139535 | false | false | false | false |
kenwilcox/AutoLayoutInCode
|
AutoLayoutInCode/ViewController.swift
|
1
|
2117
|
//
// ViewController.swift
// AutoLayoutInCode
//
// Created by Kenneth Wilcox on 11/4/15.
// Copyright © 2015 Kenneth Wilcox. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let label1 = UILabel()
label1.translatesAutoresizingMaskIntoConstraints = false
label1.backgroundColor = UIColor.redColor()
label1.text = "THESE"
let label2 = UILabel()
label2.translatesAutoresizingMaskIntoConstraints = false
label2.backgroundColor = UIColor.cyanColor()
label2.text = "ARE"
let label3 = UILabel()
label3.translatesAutoresizingMaskIntoConstraints = false
label3.backgroundColor = UIColor.yellowColor()
label3.text = "SOME"
let label4 = UILabel()
label4.translatesAutoresizingMaskIntoConstraints = false
label4.backgroundColor = UIColor.greenColor()
label4.text = "AWESOME"
let label5 = UILabel()
label5.translatesAutoresizingMaskIntoConstraints = false
label5.backgroundColor = UIColor.orangeColor()
label5.text = "LABELS"
view.addSubview(label1)
view.addSubview(label2)
view.addSubview(label3)
view.addSubview(label4)
view.addSubview(label5)
let viewsDictionary = ["label1": label1, "label2": label2, "label3": label3, "label4": label4, "label5": label5]
for label in viewsDictionary.keys {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[\(label)]|", options: [], metrics: nil, views: viewsDictionary))
}
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label1(labelHeight@999)]-[label2(label1)]-[label3(label1)]-[label4(label1)]-[label5(label1)]->=10-|", options: [], metrics: ["labelHeight": 88], views: viewsDictionary))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
mit
|
eeeb6e9c6bef4332fcb91394f6884cc7
| 32.0625 | 245 | 0.706994 | 4.540773 | false | false | false | false |
sharath-cliqz/browser-ios
|
Client/Cliqz/Foundation/AntiTracking/AntiTrackingModule.swift
|
2
|
3914
|
//
// AntiTrackingModule.swift
// Client
//
// Created by Mahmoud Adam on 8/12/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import Foundation
import JavaScriptCore
import Shared
class AntiTrackingModule: NSObject {
//MARK: Constants
fileprivate let context: JSContext? = nil
fileprivate let antiTrackingDirectory = "Extension/build/mobile/search/v8"
fileprivate let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
fileprivate let fileManager = FileManager.default
fileprivate let dispatchQueue = DispatchQueue(label: "com.cliqz.AntiTracking", attributes: [])
fileprivate let adBlockABTestPrefName = "cliqz-adb-abtest"
fileprivate let adBlockPrefName = "cliqz-adb"
fileprivate let telemetryWhiteList = ["attrack.FP", "attrack.tp_events"]
fileprivate let urlsWhiteList = ["https://cdn.cliqz.com/anti-tracking/bloom_filter/",
"https://cdn.cliqz.com/anti-tracking/whitelist/versioncheck.json",
"https://cdn.cliqz.com/adblocking/mobile/allowed-lists.json"]
let adBlockerLastUpdateDateKey = "AdBlockerLastUpdateDate"
// MARK: - Local variables
var privateMode = false
var timerCounter = 0
var timers = [Int: Timer]()
//MARK: - Singltone
static let sharedInstance = AntiTrackingModule()
override init() {
super.init()
}
//MARK: - Public APIs
func initModule() {
}
func getTrackersCount(_ webViewId: Int) -> Int {
if let webView = WebViewToUAMapper.idToWebView(webViewId) {
return webView.unsafeRequests
}
return 0
}
func getAntiTrackingStatistics(_ webViewId: Int) -> [(String, Int)] {
var antiTrackingStatistics = [(String, Int)]()
if let tabBlockInfo = getTabBlockingInfo(webViewId) {
tabBlockInfo.keys.forEach { company in
antiTrackingStatistics.append((company as! String, tabBlockInfo[company] as! Int))
}
}
return antiTrackingStatistics.sorted { $0.1 == $1.1 ? $0.0.lowercased() < $1.0.lowercased() : $0.1 > $1.1 }
}
func isDomainWhiteListed(_ hostname: String) -> Bool{
let response = Engine.sharedInstance.getBridge().callAction("antitracking:isSourceWhitelisted", args: [hostname])
if let result = response["result"] as? Bool{
return result
}
return false
}
func toggleAntiTrackingForURL(_ url: URL){
guard let host = url.host else{return}
var whitelisted = false
if self.isDomainWhiteListed(host){
self.removeFromWhitelist(host)
}
else{
self.addToWhiteList(host)
whitelisted = true
}
//Doc: If the observer checks if the website is whitelisted after this, it might get the wrong value, since the correct value may not be set yet.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationRefreshAntiTrackingButton), object: nil, userInfo: ["whitelisted":whitelisted])
}
//MARK: - Private Helpers
fileprivate func getTabBlockingInfo(_ webViewId: Int) -> [AnyHashable: Any]! {
let response = Engine.sharedInstance.getBridge().callAction("antitracking:getTrackerListForTab", args: [webViewId as AnyObject])
if let result = response["result"] {
return result as? Dictionary
} else {
return [:]
}
}
fileprivate func addToWhiteList(_ domain: String){
Engine.sharedInstance.getBridge().publishEvent("antitracking:whitelist:add", args: [domain])
}
fileprivate func removeFromWhitelist(_ domain: String){
Engine.sharedInstance.getBridge().publishEvent("antitracking:whitelist:remove", args: [domain])
}
}
|
mpl-2.0
|
e8e1c24cb8dd74c5af0a7fd797c986e7
| 34.572727 | 167 | 0.652952 | 4.446591 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application
|
Chula Expo 2017/Chula Expo 2017/Modal_EventDetails/MapTableViewCell.swift
|
1
|
2340
|
//
// MapTableViewCell.swift
// Chula Expo 2017
//
// Created by Pakpoom on 2/1/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
import MapKit
class MapTableViewCell: UITableViewCell, MKMapViewDelegate {
@IBOutlet weak var map: MKMapView!
let annotation = MKPointAnnotation()
var latitude = 13.7383829
var longitude = 100.5298641
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.layoutIfNeeded()
self.setNeedsLayout()
map.delegate = self
}
override func layoutSubviews() {
map.removeAnnotation(annotation)
let lat: CLLocationDegrees = latitude
let lon: CLLocationDegrees = longitude
let latDelta: CLLocationDegrees = 0.02
let lonDelta: CLLocationDegrees = 0.02
let location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: lon)
let span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: lonDelta)
let region: MKCoordinateRegion = MKCoordinateRegion(center: location, span: span)
map.setRegion(region, animated: true)
annotation.coordinate = location
map.addAnnotation(annotation)
map.showsUserLocation = true
map.userLocation.title = "ตำแหน่งของฉัน"
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let annotationIdentifier = "CustomerIdentifier"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier)
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotationView?.image = #imageLiteral(resourceName: "EVENT-IOS")
annotationView?.contentMode = .scaleAspectFit
annotationView?.frame = CGRect(x: (annotationView?.frame.origin.x)!, y: (annotationView?.frame.origin.y)!, width: 20, height: 29.01)
return annotationView
}
}
|
mit
|
eba649f21d2d917b54b776e2f006935d
| 29.434211 | 140 | 0.639862 | 5.546763 | false | false | false | false |
horizon-institute/babyface-ios
|
src/net/MultipartFormData.swift
|
1
|
26885
|
// MultipartFormData.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if os(iOS) || os(watchOS)
import MobileCoreServices
#elseif os(OSX)
import CoreServices
#endif
/**
Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
and the w3 form documentation.
- https://www.ietf.org/rfc/rfc2388.txt
- https://www.ietf.org/rfc/rfc2045.txt
- https://www.w3.org/TR/html401/interact/forms.html#h-17.13
*/
public class MultipartFormData {
// MARK: - Helper Types
struct EncodingCharacters {
static let CRLF = "\r\n"
}
struct BoundaryGenerator {
enum BoundaryType {
case Initial, Encapsulated, Final
}
static func randomBoundary() -> String {
return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random())
}
static func boundaryData(boundaryType boundaryType: BoundaryType, boundary: String) -> NSData {
let boundaryText: String
switch boundaryType {
case .Initial:
boundaryText = "--\(boundary)\(EncodingCharacters.CRLF)"
case .Encapsulated:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)\(EncodingCharacters.CRLF)"
case .Final:
boundaryText = "\(EncodingCharacters.CRLF)--\(boundary)--\(EncodingCharacters.CRLF)"
}
return boundaryText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
}
class BodyPart {
let headers: [String: String]
let bodyStream: NSInputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: [String: String], bodyStream: NSInputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
public var contentType: String { return "multipart/form-data; boundary=\(boundary)" }
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
private var bodyParts: [BodyPart]
private var bodyPartError: NSError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/**
Creates a multipart form data object.
- returns: The multipart form data object.
*/
public init() {
self.boundary = BoundaryGenerator.randomBoundary()
self.bodyParts = []
/**
* The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
* information, please refer to the following article:
* - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
*/
self.streamBufferSize = 1024
}
// MARK: - Body Parts
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String) {
let headers = contentHeaders(name: name)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, mimeType: String) {
let headers = contentHeaders(name: name, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the data and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter data: The data to encode into the multipart form data.
- parameter name: The name to associate with the data in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header.
*/
public func appendBodyPart(data data: NSData, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
let stream = NSInputStream(data: data)
let length = UInt64(data.length)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
- `Content-Type: #{generated mimeType}` (HTTP Header)
- Encoded file data
- Multipart form boundary
The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
`fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
system associated MIME type.
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String) {
if let
fileName = fileURL.lastPathComponent,
pathExtension = fileURL.pathExtension
{
let mimeType = mimeTypeForPathExtension(pathExtension)
appendBodyPart(fileURL: fileURL, name: name, fileName: fileName, mimeType: mimeType)
} else {
let failureReason = "Failed to extract the fileName of the provided URL: \(fileURL)"
setBodyPartError(Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason))
}
}
/**
Creates a body part from the file and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
- Content-Type: #{mimeType} (HTTP Header)
- Encoded file data
- Multipart form boundary
- parameter fileURL: The URL of the file whose content will be encoded into the multipart form data.
- parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
var isReachable = true
if #available(iOS 8.0, *)
{
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
}
guard isReachable else {
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
setBodyPartError(error)
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
guard let
path = fileURL.path
where NSFileManager.defaultManager().fileExistsAtPath(path, isDirectory: &isDirectory) && !isDirectory else
{
let failureReason = "The file URL is a directory, not a file: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
var bodyContentLength: UInt64?
do {
if let
path = fileURL.path,
fileSize = try NSFileManager.defaultManager().attributesOfItemAtPath(path)[NSFileSize] as? NSNumber
{
bodyContentLength = fileSize.unsignedLongLongValue
}
} catch {
// No-op
}
guard let length = bodyContentLength else {
let failureReason = "Could not fetch attributes from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
setBodyPartError(error)
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = NSInputStream(URL: fileURL) else {
let failureReason = "Failed to create an input stream from the file URL: \(fileURL)"
let error = Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
setBodyPartError(error)
return
}
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part from the stream and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
- `Content-Type: #{mimeType}` (HTTP Header)
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header.
- parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header.
*/
public func appendBodyPart(
stream stream: NSInputStream,
length: UInt64,
name: String,
fileName: String,
mimeType: String)
{
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
appendBodyPart(stream: stream, length: length, headers: headers)
}
/**
Creates a body part with the headers, stream and length and appends it to the multipart form data object.
The body part data will be encoded using the following format:
- HTTP headers
- Encoded stream data
- Multipart form boundary
- parameter stream: The input stream to encode in the multipart form data.
- parameter length: The content length of the stream.
- parameter headers: The HTTP headers for the body part.
*/
public func appendBodyPart(stream stream: NSInputStream, length: UInt64, headers: [String: String]) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/**
Encodes all the appended body parts into a single `NSData` object.
It is important to note that this method will load all the appended body parts into memory all at the same
time. This method should only be used when the encoded data will have a small memory footprint. For large data
cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method.
- throws: An `NSError` if encoding encounters an error.
- returns: The encoded `NSData` if encoding is successful.
*/
public func encode() throws -> NSData {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
let encoded = NSMutableData()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encodeBodyPart(bodyPart)
encoded.appendData(encodedData)
}
return encoded
}
/**
Writes the appended body parts into the given file URL.
This process is facilitated by reading and writing with input and output streams, respectively. Thus,
this approach is very memory efficient and should be used for large body part data.
- parameter fileURL: The file URL to write the multipart form data into.
- throws: An `NSError` if encoding encounters an error.
*/
public func writeEncodedDataToDisk(fileURL: NSURL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if let path = fileURL.path where NSFileManager.defaultManager().fileExistsAtPath(path) {
let failureReason = "A file already exists at the given file URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
} else if !fileURL.fileURL {
let failureReason = "The URL does not point to a valid file: \(fileURL)"
throw Error.errorWithCode(NSURLErrorBadURL, failureReason: failureReason)
}
let outputStream: NSOutputStream
if let possibleOutputStream = NSOutputStream(URL: fileURL, append: false) {
outputStream = possibleOutputStream
} else {
let failureReason = "Failed to create an output stream with the given URL: \(fileURL)"
throw Error.errorWithCode(NSURLErrorCannotOpenFile, failureReason: failureReason)
}
outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
outputStream.open()
self.bodyParts.first?.hasInitialBoundary = true
self.bodyParts.last?.hasFinalBoundary = true
for bodyPart in self.bodyParts {
try writeBodyPart(bodyPart, toOutputStream: outputStream)
}
outputStream.close()
outputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
// MARK: - Private - Body Part Encoding
private func encodeBodyPart(bodyPart: BodyPart) throws -> NSData {
let encoded = NSMutableData()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.appendData(initialData)
let headerData = encodeHeaderDataForBodyPart(bodyPart)
encoded.appendData(headerData)
let bodyStreamData = try encodeBodyStreamDataForBodyPart(bodyPart)
encoded.appendData(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.appendData(finalBoundaryData())
}
return encoded
}
private func encodeHeaderDataForBodyPart(bodyPart: BodyPart) -> NSData {
var headerText = ""
for (key, value) in bodyPart.headers {
headerText += "\(key): \(value)\(EncodingCharacters.CRLF)"
}
headerText += EncodingCharacters.CRLF
return headerText.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
}
private func encodeBodyStreamDataForBodyPart(bodyPart: BodyPart) throws -> NSData {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
var error: NSError?
let encoded = NSMutableData()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if inputStream.streamError != nil {
error = inputStream.streamError
break
}
if bytesRead > 0 {
encoded.appendBytes(buffer, length: bytesRead)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
error = Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
break
} else {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
if let error = error {
throw error
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func writeBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
try writeInitialBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeHeaderDataForBodyPart(bodyPart, toOutputStream: outputStream)
try writeBodyStreamForBodyPart(bodyPart, toOutputStream: outputStream)
try writeFinalBoundaryDataForBodyPart(bodyPart, toOutputStream: outputStream)
}
private func writeInitialBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws
{
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try writeData(initialData, toOutputStream: outputStream)
}
private func writeHeaderDataForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let headerData = encodeHeaderDataForBodyPart(bodyPart)
return try writeData(headerData, toOutputStream: outputStream)
}
private func writeBodyStreamForBodyPart(bodyPart: BodyPart, toOutputStream outputStream: NSOutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
inputStream.open()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](count: streamBufferSize, repeatedValue: 0)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw streamError
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0..<bytesRead])
}
try writeBuffer(&buffer, toOutputStream: outputStream)
} else if bytesRead < 0 {
let failureReason = "Failed to read from input stream: \(inputStream)"
throw Error.errorWithCode(.InputStreamReadFailed, failureReason: failureReason)
} else {
break
}
}
inputStream.close()
inputStream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
}
private func writeFinalBoundaryDataForBodyPart(
bodyPart: BodyPart,
toOutputStream outputStream: NSOutputStream)
throws
{
if bodyPart.hasFinalBoundary {
return try writeData(finalBoundaryData(), toOutputStream: outputStream)
}
}
// MARK: - Private - Writing Buffered Data to Output Stream
private func writeData(data: NSData, toOutputStream outputStream: NSOutputStream) throws {
var buffer = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&buffer, length: data.length)
return try writeBuffer(&buffer, toOutputStream: outputStream)
}
private func writeBuffer(inout buffer: [UInt8], toOutputStream outputStream: NSOutputStream) throws {
var bytesToWrite = buffer.count
while bytesToWrite > 0 {
if outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let streamError = outputStream.streamError {
throw streamError
}
if bytesWritten < 0 {
let failureReason = "Failed to write to output stream: \(outputStream)"
throw Error.errorWithCode(.OutputStreamWriteFailed, failureReason: failureReason)
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten..<buffer.count])
}
} else if let streamError = outputStream.streamError {
throw streamError
}
}
}
// MARK: - Private - Mime Type
private func mimeTypeForPathExtension(pathExtension: String) -> String {
if let
id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),
contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue()
{
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(name name: String) -> [String: String] {
return ["Content-Disposition": "form-data; name=\"\(name)\""]
}
private func contentHeaders(name name: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"",
"Content-Type": "\(mimeType)"
]
}
private func contentHeaders(name name: String, fileName: String, mimeType: String) -> [String: String] {
return [
"Content-Disposition": "form-data; name=\"\(name)\"; filename=\"\(fileName)\"",
"Content-Type": "\(mimeType)"
]
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> NSData {
return BoundaryGenerator.boundaryData(boundaryType: .Final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(error: NSError) {
if bodyPartError == nil {
bodyPartError = error
}
}
}
|
gpl-3.0
|
8bb6bd8be39fa40b97446cdd1d89b9c6
| 39.123881 | 128 | 0.638768 | 5.222028 | false | false | false | false |
borglab/SwiftFusion
|
Sources/BeeTracking/OISTBeeVideo+Batches.swift
|
1
|
7661
|
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import BeeDataset
import PenguinParallelWithFoundation
import PenguinStructures
import SwiftFusion
import TensorFlow
extension OISTBeeVideo {
func getUnnormalizedBatch(
_ appearanceModelSize: (Int, Int), _ batchSize: Int = 200,
randomFrameCount: Int = 10
) -> Tensor<Double> {
precondition(self.frameIds.count >= randomFrameCount, "requesting too many random frames")
var deterministicEntropy = ARC4RandomNumberGenerator(seed: 42)
let frames =
Dictionary(uniqueKeysWithValues: self.randomFrames(randomFrameCount, using: &deterministicEntropy))
let labels = frames.values.flatMap { $0.labels }
let images = labels
.randomSelectionWithoutReplacement(k: batchSize, using: &deterministicEntropy)
.map { label in
frames[label.frameIndex]!.frame.patch(at: label.location, outputSize: appearanceModelSize)
}
return Tensor(stacking: images)
}
/// Returns a `[N, h, w, c]` batch of normalized patches from bee bounding boxes, and returns the
/// statistics used to normalize them.
public func makeBatch(
appearanceModelSize: (Int, Int),
randomFrameCount: Int = 10,
batchSize: Int = 200
)
-> (normalized: Tensor<Double>, statistics: FrameStatistics)
{
let stacked = getUnnormalizedBatch(appearanceModelSize, batchSize, randomFrameCount: randomFrameCount)
let statistics = FrameStatistics(stacked)
return (statistics.normalized(stacked), statistics)
}
/// Returns a `[N, h, w, c]` batch of normalized patches from bee bounding boxes, normalized by
/// `statistics`
public func makeBatch(
statistics: FrameStatistics,
appearanceModelSize: (Int, Int), randomFrameCount: Int = 10,
batchSize: Int = 200
) -> Tensor<Double> {
let stacked = getUnnormalizedBatch(appearanceModelSize, batchSize, randomFrameCount: randomFrameCount)
return statistics.normalized(stacked)
}
/// Returns a `[N, h, w, c]` batch of normalized patches that do not overlap with any bee
/// bee bounding boxes.
public func makeBackgroundBatch(
patchSize: (Int, Int), appearanceModelSize: (Int, Int),
statistics: FrameStatistics,
randomFrameCount: Int = 10,
batchSize: Int = 200
) -> Tensor<Double> {
let images = makeBackgroundBoundingBoxes(patchSize: patchSize, batchSize: batchSize).map { (frame, obb) -> Tensor<Double> in
frame!.patch(at: obb, outputSize: appearanceModelSize)
}
let stacked = Tensor(stacking: images)
return statistics.normalized(stacked)
}
/// Returns a batch of locations of foreground
/// bee bounding boxes.
public func makeForegroundBoundingBoxes(
patchSize: (Int, Int),
batchSize: Int = 200
) -> [(frame: Tensor<Double>?, obb: OrientedBoundingBox)] {
/// Anything not completely overlapping labels
var deterministicEntropy = ARC4RandomNumberGenerator(seed: 42)
let frames = self.randomFrames(self.frames.count, using: &deterministicEntropy)
// We need `batchSize / frames.count` patches from each frame, plus the remainder of the
// integer division.
var patchesPerFrame = Array(repeating: batchSize / frames.count, count: frames.count)
patchesPerFrame[0] += batchSize % frames.count
/// Samples bounding boxes randomly from each frame
/// returns array of (ref to frame, oriented bounding box)
let obbs = zip(patchesPerFrame, frames).flatMap { args -> [(frame: Tensor<Double>?, obb: OrientedBoundingBox)] in
let (patchCount, (_, (frame, labels))) = args
let locations = labels.randomSelectionWithoutReplacement(k: patchCount, using: &deterministicEntropy).map(\.location.center)
return locations.map { location -> (frame: Tensor<Double>?, obb: OrientedBoundingBox) in
return (frame: frame, obb: OrientedBoundingBox(
center: location,
rows: patchSize.0, cols: patchSize.1))
}
}
return obbs
}
/// Returns a batch of locations of background
/// bee bounding boxes.
public func makeBackgroundBoundingBoxes(
patchSize: (Int, Int),
batchSize: Int = 200
) -> [(frame: Tensor<Double>?, obb: OrientedBoundingBox)] {
/// Anything not completely overlapping labels
let maxSide = min(patchSize.0, patchSize.1)
var deterministicEntropy = ARC4RandomNumberGenerator(seed: 42)
let frames = self.randomFrames(self.frames.count, using: &deterministicEntropy)
// We need `batchSize / frames.count` patches from each frame, plus the remainder of the
// integer division.
var patchesPerFrame = Array(repeating: batchSize / frames.count, count: frames.count)
patchesPerFrame[0] += batchSize % frames.count
let obbs = zip(patchesPerFrame, frames).flatMap { args -> [(frame: Tensor<Double>?, obb: OrientedBoundingBox)] in
let (patchCount, (_, (frame, labels))) = args
let locations = (0..<patchCount).map { _ -> Vector2 in
let attemptCount = 1000
for _ in 0..<attemptCount {
// Sample a point uniformly at random in the frame, away from the edges.
let location = Vector2(
Double.random(in: Double(maxSide)..<Double(frame.shape[1] - maxSide), using: &deterministicEntropy),
Double.random(in: Double(maxSide)..<Double(frame.shape[0] - maxSide), using: &deterministicEntropy))
// Conservatively reject any point that could possibly overlap with any of the labels.
for label in labels {
if (label.location.center.t - location).norm < Double(maxSide) {
continue
}
}
// The point was not rejected, so return it.
return location
}
fatalError("could not find backround location after \(attemptCount) attempts")
}
return locations.map { location -> (frame: Tensor<Double>?, obb: OrientedBoundingBox) in
let theta = Double.random(in: 0..<(2 * .pi), using: &deterministicEntropy)
return (frame: frame, obb: OrientedBoundingBox(
center: Pose2(Rot2(theta), location),
rows: patchSize.0, cols: patchSize.1))
}
}
return obbs
}
typealias LabeledFrame = (frameId: Int, (frame: Tensor<Double>, labels: [OISTBeeLabel]))
/// Returns `count` random frames.
private func randomFrames<R: RandomNumberGenerator>(_ count: Int, using randomness: inout R)
-> [LabeledFrame]
{
let selectedFrameIndices =
self.frameIds.indices.randomSelectionWithoutReplacement(k: count, using: &randomness)
return [LabeledFrame](
unsafeUninitializedCapacity: count
) {
(b, actualCount) -> Void in
ComputeThreadPools.local.parallelFor(n: count) { (i, _) -> Void in
let frameIndex = selectedFrameIndices[i]
let frameId = self.frameIds[frameIndex]
let frame = Tensor<Double>(self.loadFrame(frameId)!)
let labels = self.labels[frameIndex]
assert(labels.allSatisfy { $0.frameIndex == frameId })
(b.baseAddress! + i).initialize(to: (frameId, (frame, labels)))
}
actualCount = count
}
}
}
|
apache-2.0
|
d4150388afafac87a0b8e792ecad320f
| 40.863388 | 130 | 0.688291 | 4.308774 | false | false | false | false |
1985apps/PineKit
|
Pod/Classes/PineLabel.swift
|
2
|
1087
|
//
// KamaConfig.swift
// KamaUIKit
//
// Created by Prakash Raman on 13/02/16.
// Copyright © 2016 1985. All rights reserved.
//
import Foundation
import UIKit
open class PineLabel : UILabel {
open var lineSpaccing : CGFloat = 1.0 {
didSet {
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpaccing
let attributes = [NSParagraphStyleAttributeName: style]
self.attributedText = NSAttributedString(string: self.text!, attributes: attributes)
}
}
public init(){
super.init(frame: CGRect.zero)
setup()
style()
}
convenience public init(text: String){
self.init()
self.text = text
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(){
self.font = PineConfig.Font.get(PineConfig.Font.REGULAR, size: 14)
}
// THIS FUNCTION SHOULD BE OVERRIDDEN IN CASE OF SUB CLASSES
open func style(){
}
}
|
mit
|
2e73879d0106ec4db9fc47005f311f0c
| 21.625 | 96 | 0.593002 | 4.309524 | false | true | false | false |
akkakks/firefox-ios
|
Client/Frontend/Reader/ReaderModeStyleViewController.swift
|
4
|
8790
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
protocol ReaderModeStyleViewControllerDelegate {
func readerModeStyleViewController(readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle)
}
class ReaderModeStyleViewController: UIViewController {
var delegate: ReaderModeStyleViewControllerDelegate?
var readerModeStyle: ReaderModeStyle = DefaultReaderModeStyle
private let rowHeights = [72, 44, 44, 52]
private let width = 260
private var rows: [UIView] = []
private var fontTypeButtons: [FontTypeButton]!
private var fontSizeButtons: [FontSizeButton]!
private var themeButtons: [ThemeButton]!
override func viewDidLoad() {
view.backgroundColor = UIColor.grayColor()
// Our preferred content size has a fixed width and height based on the rows + padding
let height = rowHeights.reduce(0, combine: +) + (rowHeights.count - 1)
preferredContentSize = CGSize(width: width, height: height)
// Setup the rows. It is easier to setup a layout like this when we organize the buttons into rows.
let fontTypeRow = UIView(), fontSizeRow = UIView(), themeRow = UIView(), sliderRow = UIView()
rows = [fontTypeRow, fontSizeRow, themeRow, sliderRow]
for (idx, row) in enumerate(rows) {
view.addSubview(row)
// The only row with a full white background is the one with the slider. The others are the default
// clear color so that the gray dividers are visible between buttons in a row.
if row == sliderRow {
row.backgroundColor = UIColor.whiteColor()
}
row.snp_makeConstraints { make in
make.left.equalTo(self.view.snp_left)
make.right.equalTo(self.view.snp_right)
if idx == 0 {
make.top.equalTo(self.view.snp_top)
} else {
make.top.equalTo(self.rows[idx - 1].snp_bottom).offset(1)
}
make.height.equalTo(self.rowHeights[idx])
}
}
// Setup the font type buttons
fontTypeButtons = [
FontTypeButton(fontType: ReaderModeFontType.SansSerif),
FontTypeButton(fontType: ReaderModeFontType.Serif)
]
setupButtons(fontTypeButtons, inRow: fontTypeRow, action: "SELchangeFontType:")
// Setup the font size buttons
fontSizeButtons = [
FontSizeButton(fontSize: ReaderModeFontSize.Smallest),
FontSizeButton(fontSize: ReaderModeFontSize.Small),
FontSizeButton(fontSize: ReaderModeFontSize.Normal),
FontSizeButton(fontSize: ReaderModeFontSize.Large),
FontSizeButton(fontSize: ReaderModeFontSize.Largest),
]
setupButtons(fontSizeButtons, inRow: fontSizeRow, action: "SELchangeFontSize:")
// Setup the theme buttons
themeButtons = [
ThemeButton(theme: ReaderModeTheme.Light),
ThemeButton(theme: ReaderModeTheme.Dark),
ThemeButton(theme: ReaderModeTheme.Print)
]
setupButtons(themeButtons, inRow: themeRow, action: "SELchangeTheme:")
// Setup the brightness slider
let slider = UISlider()
slider.tintColor = UIColor.orangeColor()
sliderRow.addSubview(slider)
slider.addTarget(self, action: "SELchangeBrightness:", forControlEvents: UIControlEvents.ValueChanged)
slider.snp_makeConstraints { make in
make.center.equalTo(sliderRow.center)
make.width.equalTo(180)
}
// Setup initial values
selectFontType(readerModeStyle.fontType)
selectFontSize(readerModeStyle.fontSize)
selectTheme(readerModeStyle.theme)
slider.value = Float(UIScreen.mainScreen().brightness)
}
/// Setup constraints for a row of buttons. Left to right. They are all given the same width.
private func setupButtons(buttons: [UIButton], inRow row: UIView, action: Selector) {
for (idx, button) in enumerate(buttons) {
row.addSubview(button)
button.addTarget(self, action: action, forControlEvents: UIControlEvents.TouchUpInside)
button.snp_makeConstraints { make in
make.top.equalTo(row.snp_top)
if idx == 0 {
make.left.equalTo(row.snp_left)
} else {
make.left.equalTo(buttons[idx - 1].snp_right).offset(1)
}
make.bottom.equalTo(row.snp_bottom)
make.width.equalTo(self.preferredContentSize.width / CGFloat(buttons.count))
}
}
}
func SELchangeFontType(button: FontTypeButton) {
selectFontType(button.fontType)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontType(fontType: ReaderModeFontType) {
readerModeStyle.fontType = fontType
for button in fontTypeButtons {
button.selected = (button.fontType == fontType)
}
}
func SELchangeFontSize(button: FontSizeButton) {
selectFontSize(button.fontSize)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectFontSize(fontSize: ReaderModeFontSize) {
readerModeStyle.fontSize = fontSize
for button in fontSizeButtons {
button.selected = (button.fontSize == fontSize)
}
}
func SELchangeTheme(button: ThemeButton) {
selectTheme(button.theme)
delegate?.readerModeStyleViewController(self, didConfigureStyle: readerModeStyle)
}
private func selectTheme(theme: ReaderModeTheme) {
readerModeStyle.theme = theme
for button in themeButtons {
button.selected = (button.theme == theme)
}
}
func SELchangeBrightness(slider: UISlider) {
UIScreen.mainScreen().brightness = CGFloat(slider.value)
}
}
/// Custom button that knows how to show the right image and selection style for a ReaderModeFontType
/// value. Very generic now, which will change when we have more final UX assets.
class FontTypeButton: UIButton {
var fontType: ReaderModeFontType!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(fontType: ReaderModeFontType) {
self.init(frame: CGRectZero)
self.fontType = fontType
setTitle(fontType.rawValue, forState: UIControlState.Normal)
setTitleColor(UIColor.blackColor(), forState: UIControlState.Selected)
setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
backgroundColor = UIColor.whiteColor()
}
}
/// Custom button that knows how to show the right image and selection style for a ReaderModeFontSize
/// value. Very generic now, which will change when we have more final UX assets.
class FontSizeButton: UIButton {
var fontSize: ReaderModeFontSize!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(fontSize: ReaderModeFontSize) {
self.init(frame: CGRectZero)
self.fontSize = fontSize
setTitle("\(fontSize.rawValue)", forState: UIControlState.Normal)
setTitleColor(UIColor.blackColor(), forState: UIControlState.Selected)
setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
backgroundColor = UIColor.whiteColor()
}
}
/// Custom button that knows how to show the right image and selection style for a ReaderModeTheme
/// value. Very generic now, which will change when we have more final UX assets.
class ThemeButton: UIButton {
var theme: ReaderModeTheme!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(theme: ReaderModeTheme) {
self.init(frame: CGRectZero)
self.theme = theme
setTitle(theme.rawValue, forState: UIControlState.Normal)
setTitleColor(UIColor.blackColor(), forState: UIControlState.Selected)
setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
backgroundColor = UIColor.whiteColor()
}
}
|
mpl-2.0
|
ae7e406476f8a3f471a84c4ef4f338b8
| 36.408511 | 142 | 0.66496 | 5.170588 | false | false | false | false |
Johnykutty/SwiftLint
|
Tests/SwiftLintFrameworkTests/ColonRuleTests.swift
|
2
|
8058
|
//
// ColonRuleTests.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/18/16.
// Copyright © 2016 Realm. All rights reserved.
//
import SwiftLintFramework
import XCTest
class ColonRuleTests: XCTestCase {
func testColonWithDefaultConfiguration() {
// Verify Colon rule with test values for when flexible_right_spacing
// is false (default).
verifyRule(ColonRule.description)
}
// swiftlint:disable:next function_body_length
func testColonWithFlexibleRightSpace() {
// Verify Colon rule with test values for when flexible_right_spacing
// is true.
let description = RuleDescription(
identifier: ColonRule.description.identifier,
name: ColonRule.description.name,
description: ColonRule.description.description,
nonTriggeringExamples: ColonRule.description.nonTriggeringExamples + [
"let abc: Void\n",
"let abc: (Void, String, Int)\n",
"let abc: ([Void], String, Int)\n",
"let abc: [([Void], String, Int)]\n",
"func abc(def: Void) {}\n",
"let abc = [Void: Void]()\n"
],
triggeringExamples: [
"let ↓abc:Void\n",
"let ↓abc :Void\n",
"let ↓abc : Void\n",
"let ↓abc : [Void: Void]\n",
"let ↓abc : (Void, String, Int)\n",
"let ↓abc : ([Void], String, Int)\n",
"let ↓abc : [([Void], String, Int)]\n",
"let ↓abc :String=\"def\"\n",
"let ↓abc :Int=0\n",
"let ↓abc :Int = 0\n",
"let ↓abc:Int=0\n",
"let ↓abc:Int = 0\n",
"let ↓abc:Enum=Enum.Value\n",
"func abc(↓def:Void) {}\n",
"func abc(↓def :Void) {}\n",
"func abc(↓def : Void) {}\n",
"func abc(def: Void, ↓ghi :Void) {}\n",
"let abc = [Void↓:Void]()\n",
"let abc = [Void↓ : Void]()\n",
"let abc = [Void↓ : Void]()\n",
"let abc = [1: [3↓ : 2], 3: 4]\n",
"let abc = [1: [3↓ : 2], 3: 4]\n"
],
corrections: [
"let ↓abc:Void\n": "let abc: Void\n",
"let ↓abc :Void\n": "let abc: Void\n",
"let ↓abc : Void\n": "let abc: Void\n",
"let ↓abc : [Void: Void]\n": "let abc: [Void: Void]\n",
"let ↓abc : (Void, String, Int)\n": "let abc: (Void, String, Int)\n",
"let ↓abc : ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n",
"let ↓abc : [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n",
"let ↓abc :String=\"def\"\n": "let abc: String=\"def\"\n",
"let ↓abc :Int=0\n": "let abc: Int=0\n",
"let ↓abc :Int = 0\n": "let abc: Int = 0\n",
"let ↓abc:Int=0\n": "let abc: Int=0\n",
"let ↓abc:Int = 0\n": "let abc: Int = 0\n",
"let ↓abc:Enum=Enum.Value\n": "let abc: Enum=Enum.Value\n",
"func abc(↓def:Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def :Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def : Void) {}\n": "func abc(def: Void) {}\n",
"func abc(def: Void, ↓ghi :Void) {}\n": "func abc(def: Void, ghi: Void) {}\n",
"let abc = [Void↓:Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [Void↓ : Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [Void↓ : Void]()\n": "let abc = [Void: Void]()\n",
"let abc = [1: [3↓ : 2], 3: 4]\n": "let abc = [1: [3: 2], 3: 4]\n",
"let abc = [1: [3↓ : 2], 3: 4]\n": "let abc = [1: [3: 2], 3: 4]\n"
]
)
verifyRule(description, ruleConfiguration: ["flexible_right_spacing": true])
}
// swiftlint:disable:next function_body_length
func testColonWithoutApplyToDictionaries() {
let description = RuleDescription(
identifier: ColonRule.description.identifier,
name: ColonRule.description.name,
description: ColonRule.description.description,
nonTriggeringExamples: ColonRule.description.nonTriggeringExamples + [
"let abc = [Void:Void]()\n",
"let abc = [Void : Void]()\n",
"let abc = [Void: Void]()\n",
"let abc = [Void : Void]()\n",
"let abc = [1: [3 : 2], 3: 4]\n",
"let abc = [1: [3 : 2], 3: 4]\n"
],
triggeringExamples: [
"let ↓abc:Void\n",
"let ↓abc: Void\n",
"let ↓abc :Void\n",
"let ↓abc : Void\n",
"let ↓abc : [Void: Void]\n",
"let ↓abc : (Void, String, Int)\n",
"let ↓abc : ([Void], String, Int)\n",
"let ↓abc : [([Void], String, Int)]\n",
"let ↓abc: (Void, String, Int)\n",
"let ↓abc: ([Void], String, Int)\n",
"let ↓abc: [([Void], String, Int)]\n",
"let ↓abc :String=\"def\"\n",
"let ↓abc :Int=0\n",
"let ↓abc :Int = 0\n",
"let ↓abc:Int=0\n",
"let ↓abc:Int = 0\n",
"let ↓abc:Enum=Enum.Value\n",
"func abc(↓def:Void) {}\n",
"func abc(↓def: Void) {}\n",
"func abc(↓def :Void) {}\n",
"func abc(↓def : Void) {}\n",
"func abc(def: Void, ↓ghi :Void) {}\n"
],
corrections: [
"let ↓abc:Void\n": "let abc: Void\n",
"let ↓abc: Void\n": "let abc: Void\n",
"let ↓abc :Void\n": "let abc: Void\n",
"let ↓abc : Void\n": "let abc: Void\n",
"let ↓abc : [Void: Void]\n": "let abc: [Void: Void]\n",
"let ↓abc : (Void, String, Int)\n": "let abc: (Void, String, Int)\n",
"let ↓abc : ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n",
"let ↓abc : [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n",
"let ↓abc: (Void, String, Int)\n": "let abc: (Void, String, Int)\n",
"let ↓abc: ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n",
"let ↓abc: [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n",
"let ↓abc :String=\"def\"\n": "let abc: String=\"def\"\n",
"let ↓abc :Int=0\n": "let abc: Int=0\n",
"let ↓abc :Int = 0\n": "let abc: Int = 0\n",
"let ↓abc:Int=0\n": "let abc: Int=0\n",
"let ↓abc:Int = 0\n": "let abc: Int = 0\n",
"let ↓abc:Enum=Enum.Value\n": "let abc: Enum=Enum.Value\n",
"func abc(↓def:Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def: Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def :Void) {}\n": "func abc(def: Void) {}\n",
"func abc(↓def : Void) {}\n": "func abc(def: Void) {}\n",
"func abc(def: Void, ↓ghi :Void) {}\n": "func abc(def: Void, ghi: Void) {}\n"
]
)
verifyRule(description, ruleConfiguration: ["apply_to_dictionaries": false])
}
}
extension ColonRuleTests {
static var allTests: [(String, (ColonRuleTests) -> () throws -> Void)] {
return [
("testColonWithDefaultConfiguration", testColonWithDefaultConfiguration),
("testColonWithFlexibleRightSpace", testColonWithFlexibleRightSpace),
("testColonWithoutApplyToDictionaries", testColonWithoutApplyToDictionaries)
]
}
}
|
mit
|
a94ff96aa1a9a5c56820cd24b7d02ded
| 46.763636 | 94 | 0.449689 | 3.450525 | false | true | false | false |
YoungGary/Sina
|
Sina/Sina/Classes/Home首页/Oauth/OauthViewController.swift
|
1
|
5065
|
//
// OauthViewController.swift
// Sina
//
// Created by YOUNG on 16/9/8.
// Copyright © 2016年 Young. All rights reserved.
//
//获取accessToken : webview加载授权网址,然后拦截加载 截取出code 然后通过code请求accessToken
import UIKit
import SVProgressHUD
class OauthViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
setupNaviBar()
//加载webview
loadWeb()
}
}
//navibar
extension OauthViewController{
private func setupNaviBar(){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(OauthViewController.dismiss))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target:self, action: #selector(OauthViewController.fill))
title = "登录"
}
@objc private func dismiss(){//关闭
dismissViewControllerAnimated(true, completion: nil)
}
@objc private func fill(){//填充
//js
let jscode = "document.getElementById('userId').value = '18855525365'; document.getElementById('passwd').value = 'gaoyang666';"
webView.stringByEvaluatingJavaScriptFromString(jscode)
}
}
//load webVIew
extension OauthViewController{
private func loadWeb(){
guard let url : NSURL = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=122711537&redirect_uri=www.baidu.com") else{
return;
}
let request : NSURLRequest = NSURLRequest(URL: url)
webView.loadRequest(request)
}
}
//webview delegate
extension OauthViewController : UIWebViewDelegate{
func webViewDidStartLoad(webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
// SVProgressHUD.showErrorWithStatus("加载失败")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
guard let url = request.URL else{
return true
}
let absolute = url.absoluteString
guard absolute.containsString("code=") else{
return true
}
let result = absolute.componentsSeparatedByString("code=").last!
loadAccessToken(result)
return false
}
}
extension OauthViewController{
private func loadAccessToken(code : String){
let baseurl = "https://api.weibo.com/oauth2/access_token"
let app_key = "122711537"
let app_secret = "adf5c65bbeb223b613997c8b1df75918"
let redirect_uri = "http://www.baidu.com"
let parameters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "redirect_uri" : redirect_uri, "code" : code]
NetWorkTools.shareInstance.request(.POST, url: baseurl, parameters: parameters) { (result, error) in
if error != nil{
print(error)
return
}
//print(result)
guard let resultDict = result else{
print("no result")
return
}
let useraccount = UserAccount(dict: resultDict as! [String : AnyObject])
//print(userAccount)
//获取用户信息
self.loadUesrInfo(useraccount)
}
}
//获取用户信息
private func loadUesrInfo(useraccount:UserAccount){
guard let token = useraccount.access_token else{
return
}
guard let u_id = useraccount.uid else{
return
}
NetWorkTools.shareInstance.loadUserInfo(token, uid: u_id) { (result, error) in
if error != nil{
print (error)
return
}
//print (result)
guard let userInfoDict = result else{
return
}
useraccount.screen_name = userInfoDict["screen_name"] as? String
useraccount.avatar_large = userInfoDict["avatar_large"] as? String
//归档userAccount对象
//获取沙盒路径
let document = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let path = (document as NSString).stringByAppendingPathComponent("account.plist")
print(path)
NSKeyedArchiver.archiveRootObject(useraccount, toFile: path)
//把单例对象设置
UserAccountViewModel.sharedInstance.account = useraccount
self.dismissViewControllerAnimated(false, completion: {
UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
})
}
}
}
|
apache-2.0
|
23c7453ad1591f695efbd05ae4c9a88a
| 31.196078 | 161 | 0.614089 | 4.834151 | false | false | false | false |
rohan-jansen/PopKit
|
PopKit/Classes/PopKitPresentationAnimator.swift
|
1
|
5298
|
//
// PopKitPresentationAnimator.swift
// PopKit_Example
//
// Created by Rohan Jansen on 2017/08/16.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
class PopKitPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning, TransitionDuration {
var kit: PopKit
var transitionDuration: TimeInterval?
init(with kit: PopKit) {
self.kit = kit
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return kit.transitionSpeed
}
func animateSlideAndScale(_ transitionContext: UIViewControllerContextTransitioning, _ controller: PopKitPresentationController, _ initialFrame: CGRect, _ finalFrame: CGRect, _ animationOption: UIView.AnimationOptions) {
let animationDuration = transitionDuration(using: transitionContext)
controller.presentedViewController.view.frame = initialFrame
UIView.animate(withDuration: animationDuration, delay: 0, options: animationOption, animations: {
controller.presentedViewController.view.frame = finalFrame
controller.presentedViewController.view.transform = CGAffineTransform.identity
}) { finished in
transitionContext.completeTransition(finished)
}
}
func animateBounce(_ damping: Float, _ velocity: Float, _ transitionContext: UIViewControllerContextTransitioning, _ controller: PopKitPresentationController, _ initialFrame: CGRect, _ finalFrame: CGRect, _ animationOption: UIView.AnimationOptions) {
let animationDuration = transitionDuration(using: transitionContext)
controller.presentedViewController.view.frame = initialFrame
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: CGFloat(damping), initialSpringVelocity: CGFloat(velocity), options: animationOption, animations: {
controller.presentedViewController.view.frame = finalFrame
}) { finished in
transitionContext.completeTransition(finished)
}
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let containerController = transitionContext.viewController(forKey: .to)!
let controller = transitionContext.viewController(forKey: .to)?.presentationController as! PopKitPresentationController
transitionContext.containerView.addSubview(controller.presentedViewController.view)
let presentedFrame = containerController.view.frame
var initialFrame = controller.frameOfPresentedViewInContainerView
let finalFrame = controller.frameOfPresentedViewInContainerView
switch kit.inAnimation {
case .slideFromTop(let animationOption):
initialFrame.origin.y = -presentedFrame.size.height
animateSlideAndScale(transitionContext, controller, initialFrame, finalFrame, animationOption)
case .slideFromLeft(let animationOption):
initialFrame.origin.x = -presentedFrame.size.width
animateSlideAndScale(transitionContext, controller, initialFrame, finalFrame, animationOption)
case .slideFromRight(let animationOption):
initialFrame.origin.x = presentedFrame.size.width
animateSlideAndScale(transitionContext, controller, initialFrame, finalFrame, animationOption)
case .slideFromBottom(let animationOption):
initialFrame.origin.y = presentedFrame.size.height
animateSlideAndScale(transitionContext, controller, initialFrame, finalFrame, animationOption)
case .zoomIn(let scale, let animationOption):
controller.presentedViewController.view.transform = CGAffineTransform(scaleX: CGFloat(scale), y: CGFloat(scale))
animateSlideAndScale(transitionContext, controller, initialFrame, finalFrame, animationOption)
case .zoomOut(let scale, let animationOption):
controller.presentedViewController.view.transform = CGAffineTransform(scaleX: CGFloat(scale), y: CGFloat(scale))
animateSlideAndScale(transitionContext, controller, initialFrame, finalFrame, animationOption)
case .bounceFromTop(let damping, let velocity, let animationOption):
initialFrame.origin.y = -presentedFrame.size.height
animateBounce(damping, velocity, transitionContext, controller, initialFrame, finalFrame, animationOption)
case .bounceFromLeft(let damping, let velocity, let animationOption):
initialFrame.origin.x = -presentedFrame.size.width
animateBounce(damping, velocity, transitionContext, controller, initialFrame, finalFrame, animationOption)
case .bounceFromRight(let damping, let velocity, let animationOption):
initialFrame.origin.x = presentedFrame.size.width
animateBounce(damping, velocity, transitionContext, controller, initialFrame, finalFrame, animationOption)
case .bounceFromBottom(let damping, let velocity, let animationOption):
initialFrame.origin.y = presentedFrame.size.height
animateBounce(damping, velocity, transitionContext, controller, initialFrame, finalFrame, animationOption)
}
}
}
|
mit
|
05c57320eef2a53b21c205a9dc25874b
| 56.576087 | 254 | 0.736643 | 6.081515 | false | false | false | false |
tomasen/magic-move-segue
|
UIStoryboardSegueMagicMove.swift
|
1
|
2945
|
//
// UIStoryboardSegueMagicMove.swift
//
// Created by Tomasen on 1/10/16.
// Copyright © 2016 PINIDEA LLC. All rights reserved.
//
import UIKit
class UIStoryboardSegueMagicMove: UIStoryboardSegue, UIViewControllerTransitioningDelegate {
override func perform() {
// TODO:
// implement UIViewControllerTransitioningDelegate
// self.sourceViewController.transitioningDelegate = self
let srcView = self.sourceViewController.view
let dstView = self.destinationViewController.view
// UIApplication.sharedApplication().keyWindow?.insertSubview(dstView, atIndex: 0)
srcView.superview?.insertSubview(dstView, atIndex: 0)
dstView.setNeedsLayout()
dstView.layoutIfNeeded()
dstView.removeFromSuperview()
UIView.animateWithDuration(0.5,
delay: 0,
options:UIViewAnimationOptions.CurveEaseInOut,
animations: {
self.magicmoveSubviewsOfView(srcView, dstView: dstView)
}, completion: {
(value: Bool) in
if let nav = self.sourceViewController.navigationController {
nav.pushViewController(self.destinationViewController, animated: false)
} else {
self.sourceViewController
.presentViewController(
self.destinationViewController,
animated:false,
completion:nil)
}
})
}
func magicmoveSubviewsOfView(view: UIView, dstView: UIView){
if view.hidden {
return
}
if view.tag != 0 {
if let target = findSubviewInViewByTag(dstView, tag: view.tag) {
// magic move animation
let xScale = target.intrinsicContentSize().width / view.intrinsicContentSize().width
let yScale = target.intrinsicContentSize().height / view.intrinsicContentSize().height
view.transform = CGAffineTransformScale(view.transform, xScale, yScale)
view.frame = target.frame
} else {
view.alpha = 0.0
}
}
if view.subviews.count > 0{
for subview in view.subviews {
magicmoveSubviewsOfView(subview, dstView: dstView)
}
}
}
func findSubviewInViewByTag(view: UIView, tag: Int) -> UIView? {
assert(tag != 0)
if view.hidden {
return nil
}
if view.tag == tag {
return view
}
if view.subviews.count > 0{
for subview in view.subviews {
if let target = findSubviewInViewByTag(subview, tag: tag) {
return target
}
}
}
return nil
}
}
|
mit
|
98995d150922b19a5facfbe0ce7b0db5
| 32.454545 | 102 | 0.551291 | 5.554717 | false | false | false | false |
iCodeForever/ifanr
|
ifanr/ifanr/Views/DetailsView/HeaderBackView.swift
|
1
|
2345
|
//
// HeaderBackView.swift
// ifanr
//
// Created by sys on 16/7/22.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import UIKit
protocol HeaderViewDelegate {
func backButtonDidClick()
}
class HeaderBackView: UIView {
var delegate: HeaderViewDelegate?
var title: String! = "" {
didSet {
self.titleLabel.text = title
}
}
convenience init(title: String) {
self.init()
self.title = title
backgroundColor = UIColor.clear
addSubview(blurView)
addSubview(backButton)
addSubview(titleLabel)
setupLayout()
}
//MARK:-----Action Event-----
@objc fileprivate func goback() {
self.delegate?.backButtonDidClick()
}
//MARK:-----Custom Function-----
fileprivate func setupLayout() {
blurView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
backButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(15)
make.centerY.equalTo(self)
make.width.equalTo(20)
make.height.equalTo(15)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.backButton.snp.right).offset(10)
make.centerY.equalTo(self)
make.height.equalTo(40)
make.width.equalTo(100)
}
}
//MARK:-----Setter and Getter-----
fileprivate lazy var backButton: UIButton = {
let backButton: UIButton = UIButton()
backButton.setImage(UIImage(named: "ic_article_back"), for: UIControlState())
backButton.imageView?.contentMode = .scaleAspectFill
backButton.addTarget(self, action: #selector(goback), for: .touchUpInside)
return backButton
}()
fileprivate lazy var titleLabel: UILabel = {
let titleLabel: UILabel = UILabel()
titleLabel.text = self.title
titleLabel.font = UIFont.customFont_FZLTZCHJW(fontSize: 14)
return titleLabel
}()
fileprivate lazy var blurView: UIVisualEffectView = {
let blurEffect : UIBlurEffect = UIBlurEffect(style: .light)
let blurView : UIVisualEffectView = UIVisualEffectView(effect: blurEffect)
return blurView
}()
}
|
mit
|
745b03c631d6a813bf3340471399f64d
| 26.552941 | 85 | 0.593083 | 4.81893 | false | false | false | false |
oskarpearson/rileylink_ios
|
MinimedKit/Messages/CarelinkMessageBody.swift
|
1
|
1054
|
//
// CarelinkMessageBody.swift
// Naterade
//
// Created by Nathan Racklyeft on 12/26/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import Foundation
public class CarelinkLongMessageBody: MessageBody {
public static var length: Int = 65
let rxData: Data
public required init?(rxData: Data) {
var data: Data = rxData
if data.count < type(of: self).length {
data.append(contentsOf: [UInt8](repeating: 0, count: type(of: self).length - data.count))
}
self.rxData = data
}
public var txData: Data {
return rxData
}
}
public class CarelinkShortMessageBody: MessageBody {
public static var length: Int = 1
let data: Data
public convenience init() {
self.init(rxData: Data(hexadecimalString: "00")!)!
}
public required init?(rxData: Data) {
self.data = rxData
if rxData.count != type(of: self).length {
return nil
}
}
public var txData: Data {
return data
}
}
|
mit
|
57a0de163f66b65a99ed501fd1a6bcec
| 18.867925 | 101 | 0.607787 | 3.988636 | false | false | false | false |
optimizely/swift-sdk
|
Tests/TestUtils/MockLogger.swift
|
1
|
1315
|
//
// Copyright 2021, Optimizely, Inc. and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class MockLogger: OPTLogger {
static var logFound = false
static var expectedLog = ""
private static var _logLevel: OptimizelyLogLevel?
public static var logLevel: OptimizelyLogLevel {
get {
return _logLevel ?? .info
}
set (newLevel){
if _logLevel == nil {
_logLevel = newLevel
}
}
}
required public init() {
MockLogger.logLevel = .info
}
open func log(level: OptimizelyLogLevel, message: String) {
if ("[Optimizely][Error] " + message) == MockLogger.expectedLog {
MockLogger.logFound = true
}
}
}
|
apache-2.0
|
a5806a5ccfccc5eed30c15009a7c4a06
| 28.222222 | 75 | 0.636502 | 4.488055 | false | false | false | false |
testpress/ios-app
|
ios-app/Network/TPEndpoint.swift
|
1
|
9628
|
//
// TPEndpoint.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Alamofire
enum TPEndpoint {
case authenticateUser
case registerNewUser
case getExams
case getQuestions
case sendHeartBeat
case saveAnswer
case endExam
case loadAttempts
case resumeAttempt
case getCourses
case getChapters
case getContents
case getProfile
case getPosts
case getForum
case createForumPost
case getForumCategories
case getSubjectAnalytics
case getAttemptSubjectAnalytics
case getActivityFeed
case contentAttempts
case uploadImage
case getRank
case getLeaderboard
case getTargets
case getThreats
case resetPassword
case getPostCategories
case authenticateSocialUser
case getAccessCodeExams
case examsPath
case bookmarks
case bookmarkFolders
case attemptsPath
case commentsPath
case instituteSettings
case get
case post
case put
case delete
case registerDevice
case unRegisterDevice
case verifyPhoneNumber
case logout
case loginActivity
case logoutDevices
case userVideos
case dashboard
case getSSOUrl
var method: Alamofire.HTTPMethod {
switch self {
case .authenticateUser:
return .post
case .registerNewUser:
return .post
case .getExams:
return .get
case .getQuestions:
return .get
case .sendHeartBeat:
return .put
case .saveAnswer:
return .put
case .endExam:
return .put
case .loadAttempts:
return .get
case .resumeAttempt:
return .put
case .getCourses:
return .get
case .getChapters:
return .get
case .getContents:
return .get
case .getProfile:
return .get
case .getPosts:
return .get
case .getForum:
return .get
case .createForumPost:
return .post
case .getForumCategories,
.getSubjectAnalytics,
.getAttemptSubjectAnalytics,
.getRank,
.getLeaderboard,
.getTargets,
.getThreats,
.getPostCategories,
.getAccessCodeExams,
.bookmarks,
.bookmarkFolders,
.getActivityFeed:
return .get
case .get:
return .get
case .post,
.resetPassword,
.authenticateSocialUser,
.uploadImage,
.registerDevice,
.unRegisterDevice,
.verifyPhoneNumber,
.logoutDevices,
.logout,
.getSSOUrl:
return .post
case .put:
return .put
case .delete:
return .delete
default:
return .get
}
}
var urlPath: String {
switch self {
case .authenticateUser:
return "/api/v2.3/auth-token/"
case .registerNewUser:
return "/api/v2.3/register/"
case .getExams:
return "/api/v2.2/exams/"
case .sendHeartBeat:
return "heartbeat/"
case .resumeAttempt:
return "start/"
case .endExam:
return "end/"
case .getCourses:
return "/api/v2.4/courses/"
case .getChapters:
return "chapters/"
case .getProfile:
return "/api/v2.2/me/stats/"
case .getPosts:
return "/api/v2.2/posts/"
case .getForum, .createForumPost:
return "/api/v2.5/discussions/"
case .getForumCategories:
return "/api/v2.3/forum/categories/"
case .getSubjectAnalytics:
return "/api/v2.2/analytics/"
case .getAttemptSubjectAnalytics:
return "review/subjects/"
case .getActivityFeed:
return "/api/v2.4/activities/"
case .contentAttempts:
return "/api/v2.2/content_attempts/"
case .uploadImage:
return "/api/v2.2/image_upload/"
case .getRank:
return "/api/v2.2/me/rank/"
case .getLeaderboard:
return "/api/v2.2/leaderboard/"
case .getTargets:
return "/api/v2.2/me/targets/"
case .getThreats:
return "/api/v2.2/me/threats/"
case .resetPassword:
return "/api/v2.2/password/reset/"
case .getPostCategories:
return "/api/v2.2/posts/categories/"
case .authenticateSocialUser:
return "/api/v2.2/social-auth/"
case .getAccessCodeExams:
return "/api/v2.2/access_codes/"
case .examsPath:
return "/exams/"
case .bookmarks:
return "/api/v2.4/bookmarks/"
case .bookmarkFolders:
return "/api/v2.4/folders/"
case .getContents:
return "/api/v2.3/contents/"
case .attemptsPath:
return "/attempts/"
case .getQuestions:
return "/api/v2.2/questions/"
case .commentsPath:
return "/comments/"
case .instituteSettings:
return "/api/v2.3/settings/"
case .registerDevice:
return "/api/v2.2/devices/register/"
case .unRegisterDevice:
return "/api/v2.2/devices/unregister/"
case .verifyPhoneNumber:
return "/api/v2.2/verify/"
case .logout:
return "/api/v2.4/auth/logout/"
case .loginActivity:
return "/api/v2.3/me/login_activity/"
case .logoutDevices:
return "/api/v2.4/auth/logout_devices/"
case .userVideos:
return "/api/v2.4/user_videos/"
case .dashboard:
return "/api/v2.4/dashboard/"
case .getSSOUrl:
return "/api/v2.3/presigned_sso_url/"
default:
return ""
}
}
}
struct TPEndpointProvider {
var endpoint: TPEndpoint
var url: String
var queryParams: [String: String]
init(_ endpoint: TPEndpoint,
url: String = "",
queryParams: [String: String] = [String: String]()) {
self.endpoint = endpoint
self.url = url
self.queryParams = queryParams
}
init(_ endpoint: TPEndpoint,
urlPath: String,
queryParams: [String: String] = [String: String]()) {
let url = urlPath.isEmpty ? "" : Constants.BASE_URL + urlPath
self.init(endpoint, url: url, queryParams: queryParams)
}
func getUrl() -> String {
// If the given url is empty, use base url with url path
var url = self.url.isEmpty ? Constants.BASE_URL + endpoint.urlPath : self.url
if !queryParams.isEmpty {
url = url + "?"
for (i, queryParam) in queryParams.enumerated() {
let allowedCharacterSet =
(CharacterSet(charactersIn: "!*'();@&=+$,/?%#[] ").inverted)
let value = queryParam.value
.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)!
url = url + queryParam.key + "=" + value
if queryParams.count != (i + 1) {
url = url + "&"
}
}
}
return url
}
static func getBookmarkPath(bookmarkId: Int) -> String {
return TPEndpoint.bookmarks.urlPath + "\(bookmarkId)/"
}
static func getBookmarkFolderPath(folderId: Int) -> String {
return TPEndpoint.bookmarkFolders.urlPath + "\(folderId)/"
}
static func getCommentsUrl(questionId: Int) -> String {
return Constants.BASE_URL + TPEndpoint.getQuestions.urlPath + "\(questionId)"
+ TPEndpoint.commentsPath.urlPath
}
static func getContentAttemptUrl(contentID: Int) -> String {
return Constants.BASE_URL + TPEndpoint.getContents.urlPath + "\(contentID)" + TPEndpoint.attemptsPath.urlPath
}
static func getVideoAttemptPath(attemptID: Int) -> String {
return Constants.BASE_URL + TPEndpoint.userVideos.urlPath + "\(attemptID)/"
}
static func getDRMLicenseURL(contentID: Int) -> String {
return Constants.BASE_URL + "/api/v2.5/chapter_contents/\(contentID)/drm_license/"
}
}
|
mit
|
eda44b166c9fe1bccd8d3b4e771c0907
| 30.054839 | 117 | 0.578581 | 4.517597 | false | false | false | false |
alexruperez/AVPlayerItemHomeOutput
|
Core/AVPlayerItemHomeOutput.swift
|
1
|
3200
|
//
// AVPlayerItemHomeOutput.swift
// AVPlayerItemHomeOutput
//
// Created by Alex Rupérez on 14/5/17.
// Copyright © 2017 alexruperez. All rights reserved.
//
import AVFoundation
/// The AVPlayerItemHomeOutput lets you coordinate the output of content associated with your HomeKit lightbulbs.
public class AVPlayerItemHomeOutput: AVPlayerItemVideoOutput {
fileprivate var userDelegate: AVPlayerItemOutputPullDelegate?
fileprivate var userDelegateQueue: DispatchQueue?
fileprivate var displayLink: CADisplayLink!
private let playerItem: AVPlayerItem
private let colors: UInt
/**
Returns an instance of AVPlayerItemHomeOutput, initialized with the specified AVPlayerItem and the number of desired colors.
- parameter playerItem: The AVPlayerItem to extract the color information.
- parameter colors: The number of colors to extract and send to your HomeKit lightbulbs.
- returns: An instance of AVPlayerItemHomeOutput.
*/
public init(_ playerItem: AVPlayerItem, colors: UInt = 3) {
self.playerItem = playerItem
self.colors = colors
super.init(pixelBufferAttributes: nil)
super.setDelegate(self, queue: DispatchQueue(label: "AVPlayerItemHomeOutput (\(playerItem))", qos: .userInteractive, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil))
displayLink = CADisplayLink(target: self, selector: #selector(displayLinkCallback))
displayLink.add(to: .current, forMode: .defaultRunLoopMode)
displayLink.isPaused = true
}
public override func setDelegate(_ delegate: AVPlayerItemOutputPullDelegate?, queue delegateQueue: DispatchQueue? = nil) {
userDelegate = delegate
userDelegateQueue = delegateQueue
}
func displayLinkCallback() {
delegateQueue?.async {
let outputItemTime = self.itemTime(forHostTime: self.displayLink.timestamp + self.displayLink.duration)
if self.hasNewPixelBuffer(forItemTime: outputItemTime), let pixelBuffer = self.copyPixelBuffer(forItemTime: outputItemTime, itemTimeForDisplay: nil) {
HomeManager.shared.send(pixelBuffer, colors: self.colors)
}
}
}
}
extension AVPlayerItemHomeOutput: AVPlayerItemOutputPullDelegate {
public func outputMediaDataWillChange(_ sender: AVPlayerItemOutput) {
displayLink.isPaused = false
if let delegate = userDelegate {
if let delegateQueue = userDelegateQueue {
delegateQueue.async {
delegate.outputMediaDataWillChange?(sender)
}
} else {
delegate.outputMediaDataWillChange?(sender)
}
}
}
public func outputSequenceWasFlushed(_ output: AVPlayerItemOutput) {
requestNotificationOfMediaDataChange(withAdvanceInterval: 0.03)
if let delegate = userDelegate {
if let delegateQueue = userDelegateQueue {
delegateQueue.async {
delegate.outputSequenceWasFlushed?(output)
}
} else {
delegate.outputSequenceWasFlushed?(output)
}
}
}
}
|
mit
|
be5ca5f54c40d5ef9006739ab6c2aef0
| 38.481481 | 195 | 0.686054 | 5.174757 | false | false | false | false |
barteljan/VISPER
|
VISPER-Objc/Classes/PresenterObjc.swift
|
1
|
3040
|
//
// PresenterObjc.swift
// VISPER-Wireframe-Objc
//
// Created by bartel on 12.12.17.
//
import Foundation
import VISPER_Core
@objc public protocol PresenterObjcType {
func isResponsible(routeResult: RouteResultObjc, controller: UIViewController) -> Bool
func addPresentationLogic(routeResult: RouteResultObjc, controller: UIViewController) throws
}
@objc open class PresenterObjc: NSObject,Presenter,PresenterObjcType {
public let presenter: Presenter?
public let presenterObjc: PresenterObjcType?
public init(presenter: Presenter) {
self.presenter = presenter
self.presenterObjc = nil
}
public init(presenter: PresenterObjcType) {
if let presenter = presenter as? PresenterObjc {
self.presenter = presenter.presenter
self.presenterObjc = nil
} else {
self.presenter = nil
self.presenterObjc = presenter
}
}
public func isResponsible(routeResult: RouteResult, controller: UIViewController) -> Bool {
if let presenter = self.presenter {
return presenter.isResponsible(routeResult:routeResult,controller:controller)
} else if let presenterObjc = self.presenterObjc {
let routeResultObjc = RouteResultObjc(routeResult: routeResult)
return presenterObjc.isResponsible(routeResult: routeResultObjc, controller: controller)
} else {
fatalError("presenter or presenterObjc should be set")
}
}
open func isResponsible(routeResult: RouteResultObjc, controller: UIViewController) -> Bool {
if let presenter = self.presenter {
return presenter.isResponsible(routeResult:routeResult,controller:controller)
} else if let presenterObjc = self.presenterObjc {
return presenterObjc.isResponsible(routeResult: routeResult, controller: controller)
} else {
fatalError("presenter or presenterObjc should be set")
}
}
func addPresentationLogic(routeAnyResult: RouteResult, controller: UIViewController) throws {
if let presenter = self.presenter {
try presenter.addPresentationLogic(routeResult: routeAnyResult, controller: controller)
} else if let presenterObjc = self.presenterObjc {
let routeResultObjc = RouteResultObjc(routeResult: routeAnyResult)
try presenterObjc.addPresentationLogic(routeResult: routeResultObjc, controller: controller)
} else {
fatalError("presenter or presenterObjc should be set")
}
}
open func addPresentationLogic(routeResult: RouteResult, controller: UIViewController) throws {
try self.addPresentationLogic(routeAnyResult: routeResult, controller: controller)
}
open func addPresentationLogic(routeResult: RouteResultObjc, controller: UIViewController) throws {
try self.addPresentationLogic(routeAnyResult: routeResult , controller: controller)
}
}
|
mit
|
f95199409f7aa37d5a8051356b8b0f57
| 37.974359 | 104 | 0.691776 | 5.241379 | false | false | false | false |
u10int/Kinetic
|
Example/Tests/TweenableTests.swift
|
1
|
1403
|
//
// TweenableTests.swift
// Kinetic
//
// Created by Nicholas Shipes on 7/29/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
import Nimble
import Kinetic
class TweenableTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTweenableCAShapeLayer() {
let layer = CAShapeLayer()
layer.bounds = CGRect(x: 0, y: 0, width: 50.0, height: 50.0)
layer.strokeColor = UIColor.red.cgColor
layer.fillColor = UIColor.orange.cgColor
layer.lineWidth = 2.0
let expectation = XCTestExpectation(description: "animation progress done")
let tween = Tween(target: layer).to(FillColor(UIColor.green)).duration(0.5)
tween.on(.updated) { (tween) in
print(layer.fillColor)
}.on(.completed) { (tween) in
expectation.fulfill()
}
tween.play()
wait(for: [expectation], timeout: tween.duration + 1.0)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
cb1a888cebacf87f54b6eb612e1131cb
| 25.45283 | 111 | 0.648359 | 3.916201 | false | true | false | false |
sjtu-meow/iOS
|
Meow/MomentHomePageTableViewCell.swift
|
1
|
4972
|
//
// MomentTableViewCell.swift
// Meow
//
// Created by 唐楚哲 on 2017/6/30.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import UIKit
import RxSwift
import SwiftyJSON
import AlamofireImage
protocol ToggleLikeDelegate {
@discardableResult
func didToggleLike(id: Int, isLiked: Bool) -> Bool
}
protocol PostCommentDelegate {
func didPostComment(moment: Moment, content: String, from cell: MomentHomePageTableViewCell)
}
protocol MomentCellDelegate: AvatarCellDelegate, ToggleLikeDelegate, PostCommentDelegate {}
class MomentHomePageTableViewCell: UITableViewCell {
@IBOutlet weak var commentListStackView: UIStackView!
//MARK: - Property
/* user profile info */
@IBOutlet weak var avatarImageView: AvatarImageView!
@IBOutlet weak var nicknameLabel: UILabel!
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var createTimeLabel: UILabel!
/* moment */
@IBOutlet weak var momentContentLabel: UILabel!
@IBOutlet weak var mediaCollectionView: MediaCollectionView!
/* like & comment */
@IBOutlet weak var likeLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
// comment content
@IBOutlet weak var commentTextField: UITextField!
let disposeBag = DisposeBag()
var model: Moment?
var itemId : Int?
var isLiked = false
var delegate: MomentCellDelegate? {
didSet {
avatarImageView.delegate = delegate
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
translatesAutoresizingMaskIntoConstraints = false
avatarImageView.delegate = self.delegate
// mediaCollectionView.heightAnchor.constraint(equalToConstant: mediaCollectionView.contentSize.height).isActive = true
commentTextField.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(model: Moment) {
self.model = model
self.itemId = model.id
let moment = model
let profile = moment.profile
avatarImageView.configure(model: profile!)
nicknameLabel.text = profile?.nickname
bioLabel.text = profile?.bio
momentContentLabel.text = moment.content
updateLikeCountLabel()
updateCommentCountLabel()
updateCommentList()
//likeLabel.text = String(describing: moment.likeCount!)
// collection?
// likeLabel.text = String(describing: moment.like)
// commentLabel.text = String(describing: moment.comments)
// comment
// TODO
// media
//mediaCollectionView.configure(model: model)
mediaCollectionView.configure(model: moment)
setNeedsUpdateConstraints()
initLikeLabel()
createTimeLabel.text = moment.createTime!.toString()
}
func updateCommentList() {
guard let commets = model?.comments else { return }
for comment in commets {
let view = R.nib.momentCommentTableViewCell.firstView(owner: nil)!
view.configure(comment)
commentListStackView.addArrangedSubview(view)
}
}
func updateLikeCountLabel() {
likeLabel.text = "\(model!.likeCount ?? 0)"
}
func updateCommentCountLabel() {
commentLabel.text = "\(model!.commentCount ?? 0)"
}
func initLikeLabel() {
MeowAPIProvider.shared
.request(.isLikedMoment(id: itemId!))
.subscribe(onNext: {
[weak self]
json in
self?.isLiked = (json as! JSON)["liked"].bool!
self?.updateLikeLabel()
})
.addDisposableTo(disposeBag)
}
func updateLikeLabel() {
let title = isLiked ? "已赞" : "赞"
likeButton.setTitle(title, for: .normal)
}
@IBAction func toggleLike(_ sender: Any) {
delegate?.didToggleLike(id: itemId!, isLiked: self.isLiked)
isLiked = !isLiked
self.updateLikeLabel()
if (self.model != nil) {
self.model!.likeCount = self.model!.likeCount! + (isLiked ? 1 : -1)
self.updateLikeCountLabel()
}
}
@IBAction func postComment(_ sender: Any) {
}
// comment function
func clearComment() {
commentTextField.text = ""
}
}
extension MomentHomePageTableViewCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let content = commentTextField.text
delegate?.didPostComment(moment: model!, content: content!, from: self)
return true
}
}
|
apache-2.0
|
f78590c35cedcbc1881d5619bfbc9df7
| 26.780899 | 127 | 0.622447 | 5.056237 | false | false | false | false |
mobgeek/swift
|
Crie Seu Primeiro App/Desafios/Gabaritos/Gabarito Aula 01.playground/Contents.swift
|
2
|
2134
|
// Playground - noun: a place where people can play
import UIKit
/*
__ __
__ \ / __
/ \ | / \
\|/ Mobgeek
_,.---v---._
/\__/\ / \ Curso Swift em 4 semanas
\_ _/ / \
\ \_| @ __|
\ \_
\ ,__/ /
~~~`~~~~~~~~~~~~~~/~~~~
*/
/*:
# **Gabarito - Aual 01:**
1 - Constantes e variáveis devem ser declaradas antes de ser usadas. Para ter certeza que tipo de valor pode ser armazenado, você pode especificar o tipo escrevendo ": tipoEscolhido" após a variável.
Veja o seguinte exemplo:
*/
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
/*:
**Desafio 1:** Crie uma constante com um tipo explícito de `Float` e um valor de `6`.
Resposta:
*/
let constante:Float = 6
/*:
---
2 - Falhando no Playground.
**Desafio 2:** Tente remover a conversão para `String` da última linha de código. Qual é o erro que é gerado? Comente a sua resposta.
*/
let label = "The width is "
let width = 74
let widthLabel = label + String(width)
//: Resposta:
//let widthLabel = label + width
//Não é possível concatenar String com Int, deverá ser feita uma conversão do valor contido em width que é um Int (74) para um valor do tipo String ("74")
/*:
---
3 - Há uma maneira bem mais simples de incluir valores em strings: escrevendo o valor em parênteses, e escrevendo uma barra invertida ‘ \ ‘ antes do parêntese.
*/
let nome = "André"
var saldo = 0.47
var deposito = 50
/*:
**Desafio** 3: Use \( ) para comunicar o saldo da conta bancária do André após o depósito de R$50 com a função `println()`. Você precisará incluir um cálculo em uma `String` e, também incluir o nome do cliente junto com a saudação Olá.
Resposta:
*/
println("Olá \(nome), seu saldo é de \(saldo + Double(deposito)) reais")
/*:
Lembre-se que para poder realizar algum calculo aritmético com 2 ou mais variáveis ou constantes é preciso que ambas sejam do mesmo tipo, por isso tivemos que converter o valor de deposito para `Double`.
|
mit
|
6f49cfe330ef5f9edd5ee22221c83c94
| 30.712121 | 235 | 0.623805 | 3.018759 | false | false | false | false |
Skyvive/JsonObject
|
JsonObject/JsonObject+Mappers.swift
|
1
|
17938
|
//
// JsonObject+Mappers.swift
// JsonObject
//
// Created by Bradley Hilton on 3/17/15.
//
//
import Foundation
// MARK: JsonObject+Mappers
extension JsonObject {
var classOrigin: String {
let fullClassName = NSStringFromClass(self.dynamicType)
var components = fullClassName.componentsSeparatedByString(".")
components.removeLast()
return components.joinWithSeparator(".")
}
// MARK: Public Methods
func mapperForType(type: Any.Type) -> JsonMapper? {
return mapperFromCompleteDescription(completeDescription(type))
}
static func registerJsonMapper(mapper: JsonMapper) {
for (index, existingMapper) in mappers.enumerate() {
if let existingMapper = existingMapper as? JsonInternalMapper where "\(existingMapper.type)" == "\(_reflect(mapper).valueType)" {
mappers.removeAtIndex(index)
} else if "\(_reflect(existingMapper).valueType)" == "\(_reflect(mapper).valueType)" {
mappers.removeAtIndex(index)
}
}
mappers.append(mapper)
}
// MARK: Mapper Methods
static var mappers: [JsonMapper] = [NSStringMapper(), NSNumberMapper(), NSArrayMapper(), NSDictionaryMapper(), JsonObjectMapper(), OptionalMapper(), DictionaryMapper(), ArrayMapper(), StringMapper(), IntMapper(), FloatMapper(), DoubleMapper(), BoolMapper()]
private func mapperFromCompleteDescription(completeDescription: String) -> JsonMapper? {
let typeDescription = self.typeDescription(completeDescription)
if let JsonMapper = mapperFromTypeDescription(typeDescription) {
if let JsonMapper = JsonMapper as? JSONGenericMapper,
let genericMappers = genericMappersFromGenericsDescription(genericsDescription(completeDescription)) {
JsonMapper.submappers = genericMappers
}
if let JsonMapper = JsonMapper as? JsonObjectMapper,
let modelType = NSClassFromString(completeDescription) as? JsonObject.Type {
JsonMapper.modelType = modelType
}
if let JsonMapper = JsonMapper as? JsonObjectMapper,
let modelType = NSClassFromString("\(classOrigin).\(completeDescription)") as? JsonObject.Type {
JsonMapper.modelType = modelType
}
return JsonMapper
}
return nil
}
private func mapperFromTypeDescription(typeDescription: String) -> JsonMapper? {
for mapper in JsonObject.mappers {
if self.typeDescription(typeForMapper(mapper)) == typeDescription {
return mapper
}
}
if let someClass: AnyClass = NSClassFromString(typeDescription) {
return mapperFromSuperClass(someClass)
}
if let someClass: AnyClass = NSClassFromString("\(classOrigin).\(typeDescription)") {
return mapperFromSuperClass(someClass)
}
return nil
}
private func mapperFromSuperClass(someClass: AnyClass) -> JsonMapper? {
if let superclass: AnyClass = someClass.superclass() {
for mapper in JsonObject.mappers {
if typeDescription(someClass as Any.Type) == typeDescription(typeForMapper(mapper)) {
return mapper
}
}
return mapperFromSuperClass(superclass)
} else {
return nil
}
}
private func genericMappersFromGenericsDescription(genericsDescription: String) -> [JsonMapper]? {
var generics = [JsonMapper]()
for genericTypeDescription in componentsFromString(genericsDescription) {
if let genericMapper = mapperFromCompleteDescription(genericTypeDescription) {
generics.append(genericMapper)
}
}
return generics
}
// MARK: String Functions
private func componentsFromString(string: String) -> [String] {
var component = ""
var components = [String]()
let range = Range<String.Index>(start: string.startIndex, end: string.endIndex)
let options = NSStringEnumerationOptions.ByComposedCharacterSequences
var openings = 0
var closings = 0
string.enumerateSubstringsInRange(range, options: options) { (substring, substringRange, enclosingRange, shouldContinue) -> () in
if openings == closings && substring == "," {
components.append(component)
component = ""
} else {
if substring == ">" {
closings++
}
if substring == "<" {
openings++
}
component += substring!
}
}
components.append(component)
return components
}
private func completeDescription(type: Any.Type) -> String {
return "\(type)".stringByReplacingOccurrencesOfString(" ", withString: "", options: [], range: nil)
}
private func typeDescription(type: Any.Type) -> String {
return typeDescription(completeDescription(type))
}
private func typeDescription(description: String) -> String {
if let openingRange = description.rangeOfString("<", options: [], range: nil, locale: nil) where description[description.characters.count - 1] == ">" {
return description.substringWithRange(Range<String.Index>(start: description.startIndex, end: openingRange.startIndex))
} else {
return description
}
}
private func genericsDescription(type: Any.Type) -> String {
return genericsDescription(completeDescription(type))
}
private func genericsDescription(description: String) -> String {
if let openingRange = description.rangeOfString("<", options: [], range: nil, locale: nil) where description[description.characters.count - 1] == ">" {
return description.substringWithRange(Range<String.Index>(start: openingRange.endIndex, end: description.endIndex.predecessor()))
} else {
return ""
}
}
}
// MARK: Helper Functions
private func typeForMapper(mapper: JsonMapper) -> Any.Type {
if let internalMapper = mapper as? JsonInternalMapper {
return internalMapper.type
} else {
return _reflect(mapper).valueType
}
}
private func sampleInstanceForMapper(mapper: JsonMapper) -> Any? {
if let internalMapper = mapper as? JsonInternalMapper {
return internalMapper.sampleInstance
} else {
return mapper
}
}
// MARK: Internal Mappers
protocol JsonInternalMapper: JsonMapper {
var type: Any.Type { get }
var sampleInstance: Any? { get }
}
// MARK: Foundation Mappers
class NSStringMapper: JsonInternalMapper {
var type: Any.Type { get { return NSString.self } }
var sampleInstance: Any? { get { return "Hello World" as NSString } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .String(let nsstring): return nsstring
case .Number(let nsnumber): return nsnumber.stringValue
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? { return JsonValue(value: value) }
}
class NSNumberMapper: JsonInternalMapper {
var type: Any.Type { get { return NSNumber.self } }
var sampleInstance: Any? { get { return NSNumber(integer: 42) } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Number(let nsnumber): return nsnumber
case .String(let nsstring): return nsstring
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? { return JsonValue(value: value) }
}
class NSArrayMapper: JsonInternalMapper {
var type: Any.Type { get { return NSArray.self } }
var sampleInstance: Any? { get { return NSArray() } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Array(let nsarray): return nsarray
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? { return JsonValue(value: value) }
}
class NSDictionaryMapper: JsonInternalMapper {
var type: Any.Type { get { return NSDictionary.self } }
var sampleInstance: Any? { get { return NSDictionary() } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Dictionary(let nsdictionary): return nsdictionary
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? { return JsonValue(value: value) }
}
// MARK: Model Mapper
class JsonObjectMapper: JsonInternalMapper {
var modelType: JsonObject.Type = JsonObject.self
var type: Any.Type { get { return JsonObject.self } }
var sampleInstance: Any? { get { return modelType.init(dictionary: NSDictionary(), shouldValidate: false) } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Dictionary(let nsdictionary): return modelType.init(dictionary: nsdictionary, shouldValidate: true)
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let model = value as? JsonObject {
return JsonValue(value: model.dictionary)
} else {
return nil
}
}
}
// MARK: Generic Mappers
class JSONGenericMapper: JsonInternalMapper {
var submappers = [JsonMapper]()
var type: Any.Type { get { return JSONGenericMapper.self } }
var sampleInstance: Any? { get { return JSONGenericMapper() } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? { return nil }
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? { return JsonValue(value: nil) }
}
class OptionalMapper: JSONGenericMapper {
override var type: Any.Type { get { return Optional<AnyObject>.self } }
override var sampleInstance: Any? {
get {
if submappers.count > 0 {
return sampleInstanceForMapper(submappers[0])
} else {
return nil
}
}
}
override func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
if submappers.count > 0 {
return submappers[0].propertyValueFromJsonValue(value)
} else {
return nil
}
}
override func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if submappers.count > 0 {
return submappers[0].jsonValueFromPropertyValue(value)
} else {
return nil
}
}
}
class DictionaryMapper: JSONGenericMapper {
override var type: Any.Type { get { return Dictionary<String, AnyObject>.self } }
override var sampleInstance: Any? { get { return NSDictionary() } }
override func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Dictionary(let nsdictionary): return propertyValueFromDictionary(nsdictionary)
default: return nil
}
}
private func propertyValueFromDictionary(nsdictionary: NSDictionary) -> AnyObject? {
if submappers.count > 1 {
let keyMapper = submappers[0]
let valueMapper = submappers[1]
let dictionary = NSMutableDictionary()
for (key, value) in nsdictionary {
if let keyJsonValue = JsonValue(value: key),
let valueJsonValue = JsonValue(value: value),
let key: NSCopying = keyMapper.propertyValueFromJsonValue(keyJsonValue) as? NSCopying,
let value: AnyObject = valueMapper.propertyValueFromJsonValue(valueJsonValue) {
dictionary.setObject(value, forKey: key)
}
}
return dictionary
} else {
return nil
}
}
override func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let valueDictionary = value as? NSDictionary where submappers.count > 1 {
let keyMapper = submappers[0]
let valueMapper = submappers[1]
let dictionary = NSMutableDictionary()
for (key, value) in valueDictionary {
if let keyJsonObject = keyMapper.jsonValueFromPropertyValue(key),
let key = keyJsonObject.value() as? NSCopying,
let valueJsonValue = valueMapper.jsonValueFromPropertyValue(value) {
dictionary.setObject(valueJsonValue.value(), forKey: key)
}
}
return JsonValue(value: dictionary)
} else {
return nil
}
}
}
class ArrayMapper: JSONGenericMapper {
override var type: Any.Type { get { return Array<AnyObject>.self } }
override var sampleInstance: Any? { get { return NSArray() } }
override func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Array(let nsarray): return propertyValueFromArray(nsarray)
default: return nil
}
}
private func propertyValueFromArray(nsarray: NSArray) -> AnyObject? {
if submappers.count > 0 {
let submapper = submappers[0]
let array = NSMutableArray()
for value in nsarray {
if let jsonValue = JsonValue(value: value),
let object: AnyObject = submapper.propertyValueFromJsonValue(jsonValue) {
array.addObject(object)
}
}
return array
} else {
return nil
}
}
override func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let valueArray = value as? NSArray where submappers.count > 0 {
let submapper = submappers[0]
let array = NSMutableArray()
for value in valueArray {
if let jsonObject = submapper.jsonValueFromPropertyValue(value) {
array.addObject(jsonObject.value())
}
}
return JsonValue(value: array)
} else {
return nil
}
}
}
// MARK: Swift Mappers
class StringMapper: JsonInternalMapper {
var type: Any.Type { get { return String.self } }
var sampleInstance: Any? { get { return "Hello World" as String } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .String(let nsstring): return nsstring
case .Number(let nsnumber): return nsnumber.stringValue
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? { return JsonValue(value: value) }
}
class IntMapper: JsonInternalMapper {
var type: Any.Type { get { return Int.self } }
var sampleInstance: Any? { get { return 42 as Int } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Number(let nsnumber): return nsnumber.integerValue
case .String(let nsstring): return nsstring.integerValue
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let value = value as? Int {
return JsonValue(value: NSNumber(integer: value))
} else {
return nil
}
}
}
class FloatMapper: JsonInternalMapper {
var type: Any.Type { get { return Float.self } }
var sampleInstance: Any? { get { return 42.00 as Float } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Number(let nsnumber): return nsnumber.floatValue
case .String(let nsstring): return nsstring.floatValue
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let value = value as? Float {
return JsonValue(value: NSNumber(float: value))
} else {
return nil
}
}
}
class DoubleMapper: JsonInternalMapper {
var type: Any.Type { get { return Double.self } }
var sampleInstance: Any? { get { return 42.00 as Double } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Number(let nsnumber): return nsnumber.doubleValue
case .String(let nsstring): return nsstring.doubleValue
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let value = value as? Double {
return JsonValue(value: NSNumber(double: value))
} else {
return nil
}
}
}
class BoolMapper: JsonInternalMapper {
var type: Any.Type { get { return Bool.self } }
var sampleInstance: Any? { get { return true as Bool } }
func propertyValueFromJsonValue(value: JsonValue) -> AnyObject? {
switch value {
case .Number(let nsnumber): return nsnumber.boolValue
case .String(let nsstring): return nsstring.boolValue
default: return nil
}
}
func jsonValueFromPropertyValue(value: AnyObject) -> JsonValue? {
if let value = value as? Bool {
return JsonValue(value: NSNumber(bool: value))
} else {
return nil
}
}
}
|
mit
|
fbe941b59471c516633d7f0ec57687cd
| 31.913761 | 261 | 0.611495 | 4.926668 | false | false | false | false |
kalvish21/AndroidMessenger
|
AndroidMessengerMacDesktopClient/AndroidMessenger/Classes/AMHttpServer.swift
|
1
|
14641
|
//
// HttpServer.swift
// AndroidMessenger
//
// Created by Kalyan Vishnubhatla on 8/25/16.
// Copyright © 2016 Kalyan Vishnubhatla. All rights reserved.
//
import Cocoa
import Swifter
import SwiftyJSON
import libPhoneNumber_iOS
class AMHttpServer : NSObject {
private var server: HttpServer!
private let portNumber: in_port_t = 9192
private lazy var messageHandler: MessageHandler = {
return MessageHandler()
}()
private lazy var contactsHandler: ContactsHandler = {
return ContactsHandler()
}()
override init() {
super.init()
self.server = HttpServer()
self.server["/"] = { request in
return .OK(.Text(""))
}
self.server["/message/send"] = { request in
if request.method != "POST" {
return .OK(.Text(""))
}
let json: JSON = JSON(data: NSData(bytes: &request.body, length: request.body.count))
print(String(json))
self.handleMessageSent(json)
return .OK(.Text(""))
}
self.server["/message/received"] = { request in
if request.method != "POST" {
return .OK(.Text(""))
}
let json: JSON = JSON(data: NSData(bytes: &request.body, length: request.body.count))
print(String(json))
let messages = json["messages"].array
if (messages != nil) {
self.parseIncomingMessagesAndShowNotification(messages!)
}
return .OK(.Text(""))
}
self.server["/qr/connection"] = { request in
if request.method != "POST" {
return .OK(.Text(""))
}
let json: JSON = JSON(data: NSData(bytes: &request.body, length: request.body.count))
print(String(json))
let ip = json["ip"].stringValue
let port = json["port"].stringValue
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(String(format: "https://%@:%@", ip, port), forKey: fullUrlPath)
prefs.setObject(ip, forKey: ipAddress)
prefs.synchronize()
NSNotificationCenter.defaultCenter().postNotificationName(handshake, object: nil)
return .OK(.Text(""))
}
}
func startServer() {
do {
try self.server.start(self.portNumber, forceIPv4: false, priority: 0)
NSNotificationCenter.defaultCenter().postNotificationName(handshake, object: nil)
} catch let error as NSError {
NSLog("error %@", error.localizedDescription)
}
}
func stopServer() {
do {
try self.server.stop()
} catch let error as NSError {
NSLog("error %@", error.localizedDescription)
}
}
private func handleMessageSent(jsonData: JSON) {
let uuid = jsonData["uuid"]
if uuid.error != nil {
// uuid not present, user probably sent it from another application on their device
let messages = jsonData["messages"].array
if (messages != nil) {
let delegate = NSApplication.sharedApplication().delegate as! AppDelegate
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.parentContext = delegate.coreDataHandler.managedObjectContext
var id_values: Array<Int> = Array<Int>()
context.performBlock {
if (messages!.count > 0) {
for i in 0...(messages!.count-1) {
let object = messages![i]
NSLog("%@", object.stringValue)
// If the SMS id exists, move on
let objectId = Int((object["id"].stringValue))!
let type = object["type"].stringValue
if (self.messageHandler.checkIfMessageExists(context, idValue: objectId, type: type) || id_values.contains(objectId)) {
continue
}
print("GOT TO THE NEW MESSAGE!!!! ========")
print("Got message: %@", objectId)
print("Got message type: %@", type)
var sms = NSEntityDescription.insertNewObjectForEntityForName("Message", inManagedObjectContext: context) as! Message
if type == "sms" {
sms = self.messageHandler.setMessageDetailsFromJsonObject(sms, object: object, is_pending: false)
} else {
sms = self.messageHandler.setMessageDetailsFromJsonObjectForMms(context, sms: sms, dictionary: object, is_pending: false)
}
if sms.received == false {
id_values.append(objectId)
}
}
do {
try context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
delegate.coreDataHandler.managedObjectContext.performBlock({
do {
try delegate.coreDataHandler.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
})
dispatch_async(dispatch_get_main_queue(),{
let userInfo: Dictionary<String, AnyObject> = ["ids": id_values]
NSNotificationCenter.defaultCenter().postNotificationName(newMessageReceived, object: userInfo)
})
}
}
}
} else {
// uuid is present, we are getting confirmation for a message sent through our application
let delegate = NSApplication.sharedApplication().delegate as! AppDelegate
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.parentContext = delegate.coreDataHandler.managedObjectContext
let request = NSFetchRequest(entityName: "Message")
request.predicate = NSPredicate(format: "uuid = %@", jsonData["uuid"].stringValue)
var objs: [Message]?
do {
try objs = context.executeFetchRequest(request) as? [Message]
} catch let error as NSError {
NSLog("Unresolved error: %@, %@", error, error.userInfo)
}
if (objs != nil && objs!.count == 1) {
context.performBlock {
var sms = objs![0]
var original_thread_id = 0
if sms.thread_id != nil && Int(sms.thread_id!) < 0 {
// This was a new message the user typed in
original_thread_id = Int(sms.thread_id!)
}
sms = self.messageHandler.setMessageDetailsFromJsonObject(sms, object: jsonData, is_pending: false)
if original_thread_id < 0 {
// We need to update all of the other original thread_ids
let request = NSFetchRequest(entityName: "Message")
request.predicate = NSPredicate(format: "thread_id = %i", original_thread_id)
var objs: [Message]?
do {
try objs = context.executeFetchRequest(request) as? [Message]
} catch let error as NSError {
NSLog("Unresolved error: %@, %@", error, error.userInfo)
}
if objs != nil && objs?.count > 0 {
for obj in objs! {
obj.thread_id = sms.thread_id
}
}
}
do {
try context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
delegate.coreDataHandler.managedObjectContext.performBlock({
do {
try delegate.coreDataHandler.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
})
let objectID = sms.objectID
dispatch_async(dispatch_get_main_queue(),{
let current_sms = delegate.coreDataHandler.managedObjectContext.objectWithID(objectID) as! Message
let userInfo: Dictionary<String, AnyObject> = ["uuid": jsonData["uuid"].stringValue, "id": current_sms.id!, "thread_id": current_sms.thread_id!, "type": current_sms.sms!, "original_thread_id": original_thread_id]
NSNotificationCenter.defaultCenter().postNotificationName(messageSentConfirmation, object: userInfo)
})
}
}
}
}
// Parsing SMS/MMS messages from the phone
func parseIncomingMessagesAndShowNotification(messages: [JSON]) {
let delegate = NSApplication.sharedApplication().delegate as! AppDelegate
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.parentContext = delegate.coreDataHandler.managedObjectContext
var id_values: Array<Int> = Array<Int>()
NSLog("TOTAL: %i", messages.count)
context.performBlock {
var user_address: String?
var user_message: String?
var thread_id: Int?
if (messages.count > 0) {
for i in 0...(messages.count-1) {
let object = messages[i]
NSLog("%@", object.stringValue)
// If the SMS id exists, move on
let objectId = Int((object["id"].stringValue))!
let type = object["type"].stringValue
if (self.messageHandler.checkIfMessageExists(context, idValue: objectId, type: type) || id_values.contains(objectId)) {
continue
}
print("ADDING OBJECT ID ", objectId)
id_values.append(objectId)
var sms = NSEntityDescription.insertNewObjectForEntityForName("Message", inManagedObjectContext: context) as! Message
if type == "sms" {
sms = self.messageHandler.setMessageDetailsFromJsonObject(sms, object: object, is_pending: false)
} else {
sms = self.messageHandler.setMessageDetailsFromJsonObjectForMms(context, sms: sms, dictionary: object, is_pending: false)
}
user_address = sms.address!
user_message = sms.msg!
thread_id = Int(sms.thread_id!)
}
do {
try context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
delegate.coreDataHandler.managedObjectContext.performBlock({
do {
try delegate.coreDataHandler.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
})
}
dispatch_async(dispatch_get_main_queue(),{
let userInfo: Dictionary<String, AnyObject> = ["ids": id_values]
NSNotificationCenter.defaultCenter().postNotificationName(newMessageReceived, object: userInfo)
if (user_address != nil && user_message != nil) {
var title = user_address!
let phoneNumber: PhoneNumberData? = self.contactsHandler.getPhoneNumberIfContactExists(context, number: user_address!)
if phoneNumber != nil {
title = phoneNumber!.contact.name! as String
}
// Schedule a local notification
let notification = NSUserNotification()
notification.title = title
notification.subtitle = user_message!
notification.deliveryDate = NSDate()
notification.userInfo = ["thread_id": thread_id!, "phone_number": user_address!]
// Set reply field
notification.responsePlaceholder = "Reply"
notification.hasReplyButton = true
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification(notification)
var badge_count = messages.count
let count = NSUserDefaults.standardUserDefaults().objectForKey(badgeCountSoFar) as? String
if count != nil {
badge_count += Int(count!)!
}
// Set the badge notification if we are not in the fore ground
if delegate.isActive == false {
NSUserDefaults.standardUserDefaults().setObject(String(badge_count), forKey: badgeCountSoFar)
self.messageHandler.setBadgeCount()
}
}
})
}
}
}
|
mit
|
2f4bf10bedbe53158fb7c6c7782c5344
| 44.049231 | 236 | 0.481352 | 6.08226 | false | false | false | false |
sahandnayebaziz/Dana-Hills
|
Dana Hills/SchoolLoopViewController.swift
|
1
|
2297
|
//
// SchoolLoopViewController.swift
// Dana Hills
//
// Created by Sahand Nayebaziz on 9/24/16.
// Copyright © 2016 Nayebaziz, Sahand. All rights reserved.
//
import UIKit
import WebKit
class SchoolLoopViewController: UIViewController, WKNavigationDelegate {
let webView = WKWebView()
let login: SchoolLoopLogin
private let loginUrl = "https://dhhs.schoolloop.com/mobile/login"
init(withLogin login: SchoolLoopLogin) {
self.login = login
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "School Loop"
navigationController?.navigationBar.barTintColor = Colors.blue
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navigationController?.navigationBar.tintColor = UIColor.white
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(tappedDone))
view.addSubview(webView)
webView.snp.makeConstraints { make in
make.top.equalTo(topLayoutGuide.snp.bottom)
make.bottom.equalTo(bottomLayoutGuide.snp.top)
make.width.equalTo(view)
make.centerX.equalTo(view)
}
webView.navigationDelegate = self
webView.allowsBackForwardNavigationGestures = true
webView.load(URLRequest(url: URL(string: loginUrl)!))
}
private func run(javascript: String) {
webView.evaluateJavaScript(javascript, completionHandler: nil)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.url!.absoluteString == loginUrl {
run(javascript: "document.getElementsByName('login_name')[0].value='\(login.username)';")
run(javascript: "document.getElementsByName('password')[0].value='\(login.password)';")
run(javascript: "document.form.event_override.value='login';document.form.submit();")
}
}
@objc func tappedDone() {
dismiss(animated: true, completion: nil)
}
}
|
mit
|
31d0a72c60431c10b8191071a1b7b7dd
| 33.268657 | 132 | 0.662021 | 4.763485 | false | false | false | false |
grpc/grpc-swift
|
Sources/GRPC/_GRPCClientCodecHandler.swift
|
1
|
5430
|
/*
* Copyright 2020, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import NIOCore
internal class GRPCClientCodecHandler<
Serializer: MessageSerializer,
Deserializer: MessageDeserializer
> {
/// The request serializer.
private let serializer: Serializer
/// The response deserializer.
private let deserializer: Deserializer
internal init(serializer: Serializer, deserializer: Deserializer) {
self.serializer = serializer
self.deserializer = deserializer
}
}
extension GRPCClientCodecHandler: ChannelInboundHandler {
typealias InboundIn = _RawGRPCClientResponsePart
typealias InboundOut = _GRPCClientResponsePart<Deserializer.Output>
internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case let .initialMetadata(headers):
context.fireChannelRead(self.wrapInboundOut(.initialMetadata(headers)))
case let .message(messageContext):
do {
let response = try self.deserializer.deserialize(byteBuffer: messageContext.message)
context
.fireChannelRead(
self
.wrapInboundOut(.message(.init(response, compressed: messageContext.compressed)))
)
} catch {
context.fireErrorCaught(error)
}
case let .trailingMetadata(trailers):
context.fireChannelRead(self.wrapInboundOut(.trailingMetadata(trailers)))
case let .status(status):
context.fireChannelRead(self.wrapInboundOut(.status(status)))
}
}
}
extension GRPCClientCodecHandler: ChannelOutboundHandler {
typealias OutboundIn = _GRPCClientRequestPart<Serializer.Input>
typealias OutboundOut = _RawGRPCClientRequestPart
internal func write(
context: ChannelHandlerContext,
data: NIOAny,
promise: EventLoopPromise<Void>?
) {
switch self.unwrapOutboundIn(data) {
case let .head(head):
context.write(self.wrapOutboundOut(.head(head)), promise: promise)
case let .message(message):
do {
let serialized = try self.serializer.serialize(
message.message,
allocator: context.channel.allocator
)
context.write(
self.wrapOutboundOut(.message(.init(serialized, compressed: message.compressed))),
promise: promise
)
} catch {
promise?.fail(error)
context.fireErrorCaught(error)
}
case .end:
context.write(self.wrapOutboundOut(.end), promise: promise)
}
}
}
// MARK: Reverse Codec
internal class GRPCClientReverseCodecHandler<
Serializer: MessageSerializer,
Deserializer: MessageDeserializer
> {
/// The request serializer.
private let serializer: Serializer
/// The response deserializer.
private let deserializer: Deserializer
internal init(serializer: Serializer, deserializer: Deserializer) {
self.serializer = serializer
self.deserializer = deserializer
}
}
extension GRPCClientReverseCodecHandler: ChannelInboundHandler {
typealias InboundIn = _GRPCClientResponsePart<Serializer.Input>
typealias InboundOut = _RawGRPCClientResponsePart
internal func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch self.unwrapInboundIn(data) {
case let .initialMetadata(headers):
context.fireChannelRead(self.wrapInboundOut(.initialMetadata(headers)))
case let .message(messageContext):
do {
let response = try self.serializer.serialize(
messageContext.message,
allocator: context.channel.allocator
)
context.fireChannelRead(
self.wrapInboundOut(.message(.init(response, compressed: messageContext.compressed)))
)
} catch {
context.fireErrorCaught(error)
}
case let .trailingMetadata(trailers):
context.fireChannelRead(self.wrapInboundOut(.trailingMetadata(trailers)))
case let .status(status):
context.fireChannelRead(self.wrapInboundOut(.status(status)))
}
}
}
extension GRPCClientReverseCodecHandler: ChannelOutboundHandler {
typealias OutboundIn = _RawGRPCClientRequestPart
typealias OutboundOut = _GRPCClientRequestPart<Deserializer.Output>
internal func write(
context: ChannelHandlerContext,
data: NIOAny,
promise: EventLoopPromise<Void>?
) {
switch self.unwrapOutboundIn(data) {
case let .head(head):
context.write(self.wrapOutboundOut(.head(head)), promise: promise)
case let .message(message):
do {
let deserialized = try self.deserializer.deserialize(byteBuffer: message.message)
context.write(
self.wrapOutboundOut(.message(.init(deserialized, compressed: message.compressed))),
promise: promise
)
} catch {
promise?.fail(error)
context.fireErrorCaught(error)
}
case .end:
context.write(self.wrapOutboundOut(.end), promise: promise)
}
}
}
|
apache-2.0
|
b431b24b517e0f06221865600ccb2c1b
| 29.852273 | 95 | 0.709945 | 4.784141 | false | false | false | false |
exsortis/PnutKit
|
Sources/PnutKit/Models/Marker.swift
|
1
|
1300
|
import Foundation
public struct Marker {
public let id : String
public let lastReadId : String
public let percentage : Int
public let updatedAt : Date
public let version : String
public let name : String
}
extension Marker : Serializable {
public init?(from json : JSONDictionary) {
guard let id = json["id"] as? String,
let lastReadId = json["last_read_id"] as? String,
let percentage = json["percentage"] as? Int,
let u = json["updated_at"] as? String,
let updatedAt = ISO8601DateFormatter().date(from: u),
let version = json["version"] as? String,
let name = json["name"] as? String
else { return nil }
self.id = id
self.lastReadId = lastReadId
self.percentage = percentage
self.updatedAt = updatedAt
self.version = version
self.name = name
}
public func toDictionary() -> JSONDictionary {
let dict : JSONDictionary = [
"id" : id,
"last_read_id" : lastReadId,
"percentage" : percentage,
"updated_at" : ISO8601DateFormatter().string(from: updatedAt),
"version" : version,
"name" : name,
]
return dict
}
}
|
mit
|
33809d29e112c9c1566efa76a73f3486
| 26.659574 | 74 | 0.562308 | 4.545455 | false | false | false | false |
sindanar/PDStrategy
|
Example/PDStrategy/PDStrategy/TextFieldScrolCell.swift
|
1
|
2155
|
//
// TextFieldScrolCell.swift
// PDStrategy
//
// Created by Pavel Deminov on 09/01/2018.
// Copyright © 2018 Pavel Deminov. All rights reserved.
//
import UIKit
class TextFieldScrollCell: PDScrollViewCell {
var titleLabel: PDTitleLabel!
var textField: PDTextField!
var errorLabel: PDErrorLabel!
override func setup() {
weak var wSelf = self
TitleTextFieldErrorBuilder.addTitle(to: self) { (titleLabel, textField, errorLabel) in
wSelf?.titleLabel = titleLabel
wSelf?.textField = textField
wSelf?.errorLabel = errorLabel
}
//textField.delegate = self
textField?.addTarget(self, action: #selector(valueChanged), for: .editingChanged)
}
override func updateUI() {
titleLabel.text = itemInfo?.pdTitle
textField.text = itemInfo?.pdValue as? String
textField.placeholder = itemInfo?.pdPlaceholder
textField.layer.borderColor = textField.isFirstResponder ? UIColor.green.cgColor : nil
textField.layer.borderWidth = textField.isFirstResponder ? 3 / UIScreen.main.scale : 0
textField.layer.cornerRadius = 6 / UIScreen.main.scale
if let pdItem = itemInfo as? PDItem {
errorLabel?.text = pdItem.errorRule?.error;
}
}
/*
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
textField.becomeFirstResponder()
}
}
*/
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if let pdItem = itemInfo as? PDItem {
pdItem.invalidate()
}
updateUI()
reloadCellBlock?()
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateUI()
}
@objc func valueChanged() {
if let pdItem = itemInfo as? PDItem {
pdItem.value = textField?.text;
}
}
}
|
mit
|
1d8fa9f2387b8573d54af73de580d0ca
| 27.342105 | 94 | 0.611885 | 4.929062 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.