repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xmartlabs/XLForm
|
refs/heads/master
|
Examples/Swift/SwiftExample/Others/CustomCells/XLFormCustomCell.swift
|
mit
|
1
|
//
// XLFormCustomCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// 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.
let XLFormRowDescriptorTypeCustom = "XLFormRowDescriptorTypeCustom"
class XLFormCustomCell : XLFormBaseCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func configure() {
super.configure()
}
override func update() {
super.update()
// override
if let string = rowDescriptor?.value as? String {
textLabel?.text = string
}
else {
textLabel?.text = "Am a custom cell, select me!"
}
}
override func formDescriptorCellDidSelected(withForm controller: XLFormViewController!) {
// custom code here
// i.e new behaviour when cell has been selected
if let string = rowDescriptor?.value as? String , string == "Am a custom cell, select me!" {
self.rowDescriptor?.value = string
}
else {
self.rowDescriptor?.value = "I can do any custom behaviour..."
}
update()
controller.tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
}
}
|
9f33b687ee773b8bb7f23b3cd1cf140b
| 36.104478 | 100 | 0.681014 | false | false | false | false |
velvetroom/columbus
|
refs/heads/master
|
Source/View/CreateSave/VCreateSaveStatusBusy+Constants.swift
|
mit
|
1
|
import UIKit
extension VCreateSaveStatusBusy
{
struct Constants
{
static let labelBottom:CGFloat = -120
static let labelHeight:CGFloat = 60
static let labelFontSize:CGFloat = 16
static let cancelHeight:CGFloat = 55
static let cancelWidth:CGFloat = 120
static let cancelFontSize:CGFloat = 16
static let progressHeight:CGFloat = 20
}
}
|
61192ee30b79dc56ceb2e777fb176cbc
| 25.866667 | 46 | 0.669975 | false | false | false | false |
material-motion/motion-animator-objc
|
refs/heads/develop
|
tests/unit/AdditiveAnimatorTests.swift
|
apache-2.0
|
2
|
/*
Copyright 2017-present The Material Motion 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 XCTest
#if IS_BAZEL_BUILD
import MotionAnimator
#else
import MotionAnimator
#endif
class AdditiveAnimationTests: XCTestCase {
var animator: MotionAnimator!
var traits: MDMAnimationTraits!
var view: UIView!
override func setUp() {
super.setUp()
animator = MotionAnimator()
animator.additive = true
traits = MDMAnimationTraits(duration: 1)
let window = getTestHarnessKeyWindow()
view = UIView() // Need to animate a view's layer to get implicit animations.
window.addSubview(view)
// Connect our layers to the render server.
CATransaction.flush()
}
override func tearDown() {
animator = nil
traits = nil
view = nil
super.tearDown()
}
func testNumericKeyPathsAnimateAdditively() {
animator.animate(with: traits, between: [1, 0],
layer: view.layer, keyPath: .cornerRadius)
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 1,
"Expected only one animation to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first,
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertTrue(animation.isAdditive, "Animation is not additive when it should be.")
}
func testCGSizeKeyPathsAnimateAdditively() {
animator.animate(with: traits, between: [CGSize(width: 0, height: 0),
CGSize(width: 1, height: 2)],
layer: view.layer, keyPath: .shadowOffset)
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 1,
"Expected only one animation to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first,
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertTrue(animation.isAdditive, "Animation is not additive when it should be.")
}
func testCGPointKeyPathsAnimateAdditively() {
animator.animate(with: traits, between: [CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 2)],
layer: view.layer, keyPath: .position)
XCTAssertNotNil(view.layer.animationKeys(),
"Expected an animation to be added, but none were found.")
guard let animationKeys = view.layer.animationKeys() else {
return
}
XCTAssertEqual(animationKeys.count, 1,
"Expected only one animation to be added, but the following were found: "
+ "\(animationKeys).")
guard let key = animationKeys.first,
let animation = view.layer.animation(forKey: key) as? CABasicAnimation else {
return
}
XCTAssertTrue(animation.isAdditive, "Animation is not additive when it should be.")
}
}
|
45877e628d4d46232b94ab1c53dbc1dc
| 32.657895 | 92 | 0.664842 | false | true | false | false |
Candyroot/DesignPattern
|
refs/heads/master
|
command/command/main.swift
|
apache-2.0
|
1
|
//
// main.swift
// command
//
// Created by Bing Liu on 11/12/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
//var remote: SimpleRemoteControl = SimpleRemoteControl()
//var light: Light = Light()
//var garageDoor: GarageDoor = GarageDoor()
//var lightOn: LightOnCommand = LightOnCommand(light: light)
//var garageDoorUp: GarageDoorUpCommand = GarageDoorUpCommand(garageDoor: garageDoor)
//
//remote.setCommand(lightOn)
//remote.buttonWasPressed()
//remote.setCommand(garageDoorUp)
//remote.buttonWasPressed()
//var remoteControl = RemoteControl()
//
//var livingRoomLight = Light(name: "Living Room")
//var kitchenLight = Light(name: "Kitchen")
//var ceilingFan = CeilingFan(name: "Living Room")
//var garageDoor = GarageDoor(name: "")
//var stereo = Stereo(name: "Living Room")
//
//var livingRoomLightOn = LightOnCommand(light: livingRoomLight)
//var livingRoomLightOff = LightOffCommand(light: livingRoomLight)
//var kitchenLightOn = LightOnCommand(light: kitchenLight)
//var kitchenLightOff = LightOffCommand(light: kitchenLight)
//
//var ceilingFanOn = CeilingFanOnCommand(ceilingFan: ceilingFan)
//var ceilingFanOff = CeilingFanOffCommand(ceilingFan: ceilingFan)
//
//var garageDoorUp = GarageDoorUpCommand(garageDoor: garageDoor)
//var garageDoorDown = GarageDoorDownCommand(garageDoor: garageDoor)
//
//var stereoOnWithCD = StereoOnWithCDCommand(stereo: stereo)
//var stereoOff = StereoOffCommand(stereo: stereo)
//
//remoteControl.setCommand(0, onCommand: livingRoomLightOn, offCommand: livingRoomLightOff)
//remoteControl.setCommand(1, onCommand: kitchenLightOn, offCommand: kitchenLightOff)
//remoteControl.setCommand(2, onCommand: ceilingFanOn, offCommand: ceilingFanOff)
//remoteControl.setCommand(3, onCommand: stereoOnWithCD, offCommand: stereoOff)
//
//println(remoteControl.description)
//
//remoteControl.onButtonWasPushed(0)
//remoteControl.offButtonWasPushed(0)
//remoteControl.onButtonWasPushed(1)
//remoteControl.offButtonWasPushed(1)
//remoteControl.onButtonWasPushed(2)
//remoteControl.offButtonWasPushed(2)
//remoteControl.onButtonWasPushed(3)
//remoteControl.offButtonWasPushed(3)
//
//remoteControl.onButtonWasPushed(0)
//remoteControl.offButtonWasPushed(0)
//println(remoteControl.description)
//remoteControl.undoButtonWasPushed()
//remoteControl.offButtonWasPushed(0)
//remoteControl.onButtonWasPushed(0)
//println(remoteControl.description)
//remoteControl.undoButtonWasPushed()
//var remoteControl = RemoteControl()
//let ceilingFan = CeilingFan(name: "Living Room")
//let ceilingFanMedium = CeilingFanMediumCommand(ceilingFan: ceilingFan)
//let ceilingFanHigh = CeilingFanHighCommand(ceilingFan: ceilingFan)
//let ceilingFanOff = CeilingFanOffCommand(ceilingFan: ceilingFan)
//remoteControl.setCommand(0, onCommand: ceilingFanMedium, offCommand: ceilingFanOff)
//remoteControl.setCommand(1, onCommand: ceilingFanHigh, offCommand: ceilingFanOff)
//remoteControl.onButtonWasPushed(0)
//remoteControl.offButtonWasPushed(0)
//println(remoteControl.description)
//remoteControl.undoButtonWasPushed()
//
//remoteControl.onButtonWasPushed(1)
//println(remoteControl.description)
//remoteControl.undoButtonWasPushed()
let light = Light(name: "Living Room")
let ceilingFan = CeilingFan(name: "Living Room")
let garageDoor = GarageDoor()
let stereo = Stereo(name: "Living Room")
let lightOn = LightOnCommand(light: light)
let ceilingFanOn = CeilingFanOnCommand(ceilingFan: ceilingFan)
let garageDoorUp = GarageDoorUpCommand(garageDoor: garageDoor)
let stereoOn = StereoOnWithCDCommand(stereo: stereo)
let lightOff = LightOffCommand(light: light)
let ceilingFanOff = CeilingFanOffCommand(ceilingFan: ceilingFan)
let garageDoorDown = GarageDoorDownCommand(garageDoor: garageDoor)
let stereoOff = StereoOffCommand(stereo: stereo)
let partyOn: [Command] = [lightOn, ceilingFanOn, garageDoorUp, stereoOn]
let partyOff: [Command] = [lightOff, ceilingFanOff, garageDoorDown, stereoOff]
let partyOnMacro = MacroCommand(commands: partyOn)
let partyOffMacro = MacroCommand(commands: partyOff)
let remoteControl = RemoteControl()
remoteControl.setCommand(0, onCommand: partyOnMacro, offCommand: partyOffMacro)
println(remoteControl.description)
println("--- Pushing Macro On ---")
remoteControl.onButtonWasPushed(0)
println("--- Pushing Macro Off ---")
remoteControl.offButtonWasPushed(0)
println("--- Pushing Macro Undo ---")
remoteControl.undoButtonWasPushed()
|
85385a39e45b505723f472212a75e6a0
| 36.803419 | 91 | 0.797196 | false | false | false | false |
Paludis/Swifter
|
refs/heads/master
|
Swifter/SwifterUsers.swift
|
mit
|
2
|
//
// SwifterUsers.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
public extension Swifter {
/*
GET account/settings
Returns settings (including current trend, geo and sleep time information) for the authenticating user.
*/
public func getAccountSettingsWithSuccess(success: ((settings: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "account/settings.json"
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(settings: json.object)
return
}, failure: failure)
}
/*
GET account/verify_credentials
Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid.
*/
public func getAccountVerifyCredentials(includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((myInfo: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "account/verify_credentials.json"
var parameters = Dictionary<String, Any>()
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(myInfo: json.object)
return
}, failure: failure)
}
/*
POST account/settings
Updates the authenticating user's settings.
*/
public func postAccountSettings(trendLocationWOEID: Int? = nil, sleepTimeEnabled: Bool? = nil, startSleepTime: Int? = nil, endSleepTime: Int? = nil, timeZone: String? = nil, lang: String? = nil, success: ((settings: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
assert(trendLocationWOEID != nil || sleepTimeEnabled != nil || startSleepTime != nil || endSleepTime != nil || timeZone != nil || lang != nil, "At least one or more should be provided when executing this request")
let path = "account/settings.json"
var parameters = Dictionary<String, Any>()
if trendLocationWOEID != nil {
parameters["trend_location_woeid"] = trendLocationWOEID!
}
if sleepTimeEnabled != nil {
parameters["sleep_time_enabled"] = sleepTimeEnabled!
}
if startSleepTime != nil {
parameters["start_sleep_time"] = startSleepTime!
}
if endSleepTime != nil {
parameters["end_sleep_time"] = endSleepTime!
}
if timeZone != nil {
parameters["time_zone"] = timeZone!
}
if lang != nil {
parameters["lang"] = lang!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(settings: json.object)
return
}, failure: failure)
}
/*
POST account/update_delivery_device
Sets which device Twitter delivers updates to for the authenticating user. Sending none as the device parameter will disable SMS updates.
*/
public func postAccountUpdateDeliveryDeviceSMS(device: Bool, includeEntities: Bool? = nil, success: ((deliveryDeviceSettings: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "account/update_delivery_device.json"
var parameters = Dictionary<String, Any>()
if device {
parameters["device"] = "sms"
}
else {
parameters["device"] = "none"
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(deliveryDeviceSettings: json.object)
return
}, failure: failure)
}
/*
POST account/update_profile
Sets values that users are able to set under the "Account" tab of their settings page. Only the parameters specified will be updated.
*/
public func postAccountUpdateProfileWithName(name: String? = nil, url: String? = nil, location: String? = nil, description: String? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((profile: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
assert(name != nil || url != nil || location != nil || description != nil || includeEntities != nil || skipStatus != nil)
let path = "account/update_profile.json"
var parameters = Dictionary<String, Any>()
if name != nil {
parameters["name"] = name!
}
if url != nil {
parameters["url"] = url!
}
if location != nil {
parameters["location"] = location!
}
if description != nil {
parameters["description"] = description!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(profile: json.object)
return
}, failure: failure)
}
/*
POST account/update_profile_background_image
Updates the authenticating user's profile background image. This method can also be used to enable or disable the profile background image. Although each parameter is marked as optional, at least one of image, tile or use must be provided when making this request.
*/
public func postAccountUpdateProfileBackgroundImage(imageData: NSData? = nil, title: String? = nil, includeEntities: Bool? = nil, use: Bool? = nil, success: ((profile: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
assert(imageData != nil || title != nil || use != nil, "At least one of image, tile or use must be provided when making this request")
let path = "account/update_profile_background_image.json"
var parameters = Dictionary<String, Any>()
if imageData != nil {
parameters["image"] = imageData!.base64EncodedStringWithOptions([])
}
if title != nil {
parameters["title"] = title!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if use != nil {
parameters["use"] = use!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(profile: json.object)
return
}, failure: failure)
}
/*
POST account/update_profile_colors
Sets one or more hex values that control the color scheme of the authenticating user's profile page on twitter.com. Each parameter's value must be a valid hexidecimal value, and may be either three or six characters (ex: #fff or #ffffff).
*/
public func postUpdateAccountProfileColors(profileBackgroundColor: String? = nil, profileLinkColor: String? = nil, profileSidebarBorderColor: String? = nil, profileSidebarFillColor: String? = nil, profileTextColor: String? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((profile: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "account/update_profile_colors.json"
var parameters = Dictionary<String, Any>()
if profileBackgroundColor != nil {
parameters["profile_background_color"] = profileBackgroundColor!
}
if profileLinkColor != nil {
parameters["profile_link_color"] = profileLinkColor!
}
if profileSidebarBorderColor != nil {
parameters["profile_sidebar_link_color"] = profileSidebarBorderColor!
}
if profileSidebarFillColor != nil {
parameters["profile_sidebar_fill_color"] = profileSidebarFillColor!
}
if profileTextColor != nil {
parameters["profile_text_color"] = profileTextColor!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(profile: json.object)
return
}, failure: failure)
}
/*
POST account/update_profile_image
Updates the authenticating user's profile image. Note that this method expects raw multipart data, not a URL to an image.
This method asynchronously processes the uploaded file before updating the user's profile image URL. You can either update your local cache the next time you request the user's information, or, at least 5 seconds after uploading the image, ask for the updated URL using GET users/show.
*/
public func postAccountUpdateProfileImage(imageData: NSData? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((profile: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "account/update_profile_image.json"
var parameters = Dictionary<String, Any>()
if imageData != nil {
parameters["image"] = imageData!.base64EncodedStringWithOptions([])
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(profile: json.object)
return
}, failure: failure)
}
/*
GET blocks/list
Returns a collection of user objects that the authenticating user is blocking.
*/
public func getBlockListWithIncludeEntities(includeEntities: Bool? = nil, skipStatus: Bool? = nil, cursor: Int? = nil, success: ((users: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "blocks/list.json"
var parameters = Dictionary<String, Any>()
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
if cursor != nil {
parameters["cursor"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json["users"].array, previousCursor: json["previous_cursor"].integer, nextCursor: json["next_cursor"].integer)
}, failure: failure)
}
/*
GET blocks/ids
Returns an array of numeric user ids the authenticating user is blocking.
*/
public func getBlockIDsWithStingifyIDs(stringifyIDs: String? = nil, cursor: Int? = nil, success: ((ids: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)? = nil, failure: FailureHandler) {
let path = "blocks/ids.json"
var parameters = Dictionary<String, Any>()
if stringifyIDs != nil {
parameters["stringify_ids"] = stringifyIDs!
}
if cursor != nil {
parameters["cursor"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(ids: json["ids"].array, previousCursor: json["previous_cursor"].integer, nextCursor: json["next_cursor"].integer)
}, failure: failure)
}
/*
POST blocks/create
Blocks the specified user from following the authenticating user. In addition the blocked user will not show in the authenticating users mentions or timeline (unless retweeted by another user). If a follow or friend relationship exists it is destroyed.
*/
public func postBlocksCreateWithScreenName(screenName: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "blocks/create.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
public func postBlocksCreateWithUserID(userID: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "blocks/create.json"
var parameters = Dictionary<String, Any>()
parameters["user_id"] = userID
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
/*
POST blocks/destroy
Un-blocks the user specified in the ID parameter for the authenticating user. Returns the un-blocked user in the requested format when successful. If relationships existed before the block was instated, they will not be restored.
*/
public func postDestroyBlocksWithUserID(userID: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "blocks/destroy.json"
var parameters = Dictionary<String, Any>()
parameters["user_id"] = userID
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
public func postDestroyBlocksWithScreenName(screenName: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "blocks/destroy.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
/*
GET users/lookup
Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
This method is especially useful when used in conjunction with collections of user IDs returned from GET friends/ids and GET followers/ids.
GET users/show is used to retrieve a single user object.
There are a few things to note when using this method.
- You must be following a protected user to be able to see their most recent status update. If you don't follow a protected user their status will be removed.
- The order of user IDs or screen names may not match the order of users in the returned array.
- If a requested user is unknown, suspended, or deleted, then that user will not be returned in the results list.
- If none of your lookup criteria can be satisfied by returning a user object, a HTTP 404 will be thrown.
- You are strongly encouraged to use a POST for larger requests.
*/
public func getUsersLookupWithScreenNames(screenNames: [String], includeEntities: Bool? = nil, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler) {
let path = "users/lookup.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenNames.joinWithSeparator(",")
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
public func getUsersLookupWithUserIDs(userIDs: [String], includeEntities: Bool? = nil, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler) {
let path = "users/lookup.json"
var parameters = Dictionary<String, Any>()
let userIDStrings = userIDs.map { String($0) }
parameters["user_id"] = userIDStrings.joinWithSeparator(",")
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
/*
GET users/show
Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible. GET users/lookup is used to retrieve a bulk collection of user objects.
You must be following a protected user to be able to see their most recent Tweet. If you don't follow a protected user, the users Tweet will be removed. A Tweet will not always be returned in the current_status field.
*/
public func getUsersShowWithScreenName(screenName: String, includeEntities: Bool? = nil, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "users/show.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
public func getUsersShowWithUserID(userID: String, includeEntities: Bool? = nil, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler) {
let path = "users/show.json"
var parameters = Dictionary<String, Any>()
parameters["user_id"] = userID
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
/*
GET users/search
Provides a simple, relevance-based search interface to public user accounts on Twitter. Try querying by topical interest, full name, company name, location, or other criteria. Exact match searches are not supported.
Only the first 1,000 matching results are available.
*/
public func getUsersSearchWithQuery(q: String, page: Int?, count: Int?, includeEntities: Bool?, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler) {
let path = "users/search.json"
var parameters = Dictionary<String, Any>()
parameters["q"] = q
if page != nil {
parameters["page"] = page!
}
if count != nil {
parameters["count"] = count!
}
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
/*
GET users/contributees
Returns a collection of users that the specified user can "contribute" to.
*/
public func getUsersContributeesWithUserID(id: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "users/contributees.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
public func getUsersContributeesWithScreenName(screenName: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "users/contributees.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
/*
GET users/contributors
Returns a collection of users who can contribute to the specified account.
*/
public func getUsersContributorsWithUserID(id: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "users/contributors.json"
var parameters = Dictionary<String, Any>()
parameters["id"] = id
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
public func getUsersContributorsWithScreenName(screenName: String, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((users: [JSONValue]?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "users/contributors.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json.array)
return
}, failure: failure)
}
/*
POST account/remove_profile_banner
Removes the uploaded profile banner for the authenticating user. Returns HTTP 200 upon success.
*/
public func postAccountRemoveProfileBannerWithSuccess(success: ((response: JSON) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "account/remove_profile_banner.json"
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(response: json)
return
}, failure: failure)
}
/*
POST account/update_profile_banner
Uploads a profile banner on behalf of the authenticating user. For best results, upload an <5MB image that is exactly 1252px by 626px. Images will be resized for a number of display options. Users with an uploaded profile banner will have a profile_banner_url node in their Users objects. More information about sizing variations can be found in User Profile Images and Banners and GET users/profile_banner.
Profile banner images are processed asynchronously. The profile_banner_url and its variant sizes will not necessary be available directly after upload.
If providing any one of the height, width, offset_left, or offset_top parameters, you must provide all of the sizing parameters.
HTTP Response Codes
200, 201, 202 Profile banner image succesfully uploaded
400 Either an image was not provided or the image data could not be processed
422 The image could not be resized or is too large.
*/
public func postAccountUpdateProfileBannerWithImageData(imageData: NSData? = nil, width: Int? = nil, height: Int? = nil, offsetLeft: Int? = nil, offsetTop: Int? = nil, success: ((response: JSON) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "account/update_profile_banner.json"
var parameters = Dictionary<String, Any>()
if imageData != nil {
parameters["banner"] = imageData!.base64EncodedStringWithOptions([])
}
if width != nil {
parameters["width"] = width!
}
if height != nil {
parameters["height"] = height!
}
if offsetLeft != nil {
parameters["offset_left"] = offsetLeft!
}
if offsetTop != nil {
parameters["offset_top"] = offsetTop!
}
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(response: json)
return
}, failure: failure)
}
/*
GET users/profile_banner
Returns a map of the available size variations of the specified user's profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. This method can be used instead of string manipulation on the profile_banner_url returned in user objects as described in User Profile Images and Banners.
*/
public func getUsersProfileBannerWithUserID(userID: String, success: ((response: JSON) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "users/profile_banner.json"
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: [:], uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(response: json)
return
}, failure: failure)
}
/*
POST mutes/users/create
Mutes the user specified in the ID parameter for the authenticating user.
Returns the muted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
Actions taken in this method are asynchronous and changes will be eventually consistent.
*/
public func postMutesUsersCreateForScreenName(screenName: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "mutes/users/create.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
public func postMutesUsersCreateForUserID(userID: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "mutes/users/create.json"
var parameters = Dictionary<String, Any>()
parameters["user_id"] = userID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
/*
POST mutes/users/destroy
Un-mutes the user specified in the ID parameter for the authenticating user.
Returns the unmuted user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
Actions taken in this method are asynchronous and changes will be eventually consistent.
*/
public func postMutesUsersDestroyForScreenName(screenName: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "mutes/users/destroy.json"
var parameters = Dictionary<String, Any>()
parameters["screen_name"] = screenName
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
public func postMutesUsersDestroyForUserID(userID: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "mutes/users/destroy.json"
var parameters = Dictionary<String, Any>()
parameters["user_id"] = userID
self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(user: json.object)
return
}, failure: failure)
}
/*
GET mutes/users/ids
Returns an array of numeric user ids the authenticating user has muted.
*/
public func getMutesUsersIDsWithCursor(cursor: Int? = nil, success: ((ids: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "mutes/users/ids.json"
var parameters = Dictionary<String, Any>()
if cursor != nil {
parameters["cursor"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(ids: json["ids"].array, previousCursor: json["previous_cursor"].integer, nextCursor: json["next_cursor"].integer)
}, failure: failure)
}
/*
GET mutes/users/list
Returns an array of user objects the authenticating user has muted.
*/
public func getMutesUsersListWithCursor(cursor: Int? = nil, includeEntities: Bool? = nil, skipStatus: Bool? = nil, success: ((users: [JSONValue]?, previousCursor: Int?, nextCursor: Int?) -> Void)? = nil, failure: FailureHandler? = nil) {
let path = "mutes/users/list.json"
var parameters = Dictionary<String, Any>()
if includeEntities != nil {
parameters["include_entities"] = includeEntities!
}
if skipStatus != nil {
parameters["skip_status"] = skipStatus!
}
if cursor != nil {
parameters["cursor"] = cursor!
}
self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: {
json, response in
success?(users: json["users"].array, previousCursor: json["previous_cursor"].integer, nextCursor: json["next_cursor"].integer)
}, failure: failure)
}
}
|
d9b86e48679204dac42864941e161025
| 39.551963 | 411 | 0.640441 | false | false | false | false |
bay2/LetToDo
|
refs/heads/master
|
LetToDo/Task/Model/ToDoModel.swift
|
mit
|
1
|
//
// ToDoModel.swift
// LetToDo
//
// Created by xuemincai on 16/9/21.
// Copyright © 2016年 xuemincai. All rights reserved.
//
import Foundation
import RealmSwift
class ToDoModel: Object {
/// ID
dynamic var taskID = UUID().uuidString
/// 任务名
dynamic var taskName = ""
/// 已完成
dynamic var isDone = false
override static func primaryKey() -> String? {
return "taskID"
}
// Specify properties to ignore (Realm won't persist these)
// override static func ignoredProperties() -> [String] {
// return []
// }
}
extension ToDoModel {
convenience init(taskName: String, isDone: Bool = false) {
self.init()
self.taskName = taskName
self.isDone = isDone
}
convenience init(taskID: String, taskName: String, isDone: Bool) {
self.init()
self.taskID = taskID
self.taskName = taskName
self.isDone = isDone
}
}
|
04d71246489489519e6afe8735653e54
| 16.525424 | 70 | 0.552224 | false | false | false | false |
nkirby/Humber
|
refs/heads/master
|
_lib/HMGithub/_src/Model/GithubNotificationModel.swift
|
mit
|
1
|
// =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import RealmSwift
// =======================================================
public struct GithubNotificationModel {
public let notificationID: String
public let unread: Bool
public let reason: GithubNotificationReason
public let title: String
public let subjectURL: String
public let latestCommentURL: String
public let type: GithubNotificationType
public let repository: GithubRepoModel
// =======================================================
// MARK: - Response -> Model
public init(response: GithubNotificationResponse) {
self.notificationID = response.notificationID
self.unread = response.unread
self.reason = response.reason
self.title = response.title
self.subjectURL = response.subjectURL
self.latestCommentURL = response.latestCommentURL
self.type = response.type
self.repository = GithubRepoModel(response: response.repository)
}
// =======================================================
// MARK: - Object -> Model
public init?(object: GithubNotification) {
self.notificationID = object.notificationID
self.unread = object.unread
self.reason = GithubNotificationReason(rawValue: object.reason) ?? GithubNotificationReason.Subscribed
self.title = object.title
self.subjectURL = object.subjectURL
self.latestCommentURL = object.latestCommentURL
self.type = GithubNotificationType(rawValue: object.type) ?? GithubNotificationType.Issue
if let repo = object.repository {
self.repository = GithubRepoModel(object: repo)
} else {
return nil
}
}
}
|
0f9957e68c62b47708b5fdce3b834a11
| 31.689655 | 110 | 0.57173 | false | true | false | false |
wireapp/wire-ios-sync-engine
|
refs/heads/develop
|
Source/Notifications/Push notifications/Notification Types/LocalNotificationType+Localization.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 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 Foundation
// These are the "base" keys for messages. We append to these for the specific case.
//
private let ZMPushStringDefault = "default"
private let ZMPushStringEphemeralTitle = "ephemeral.title"
private let ZMPushStringEphemeral = "ephemeral"
// Title with team name
private let ZMPushStringTitle = "title" // "[conversationName] in [teamName]
// 1 user, 1 conversation, 1 string
// %1$@ %2$@ %3$@
//
private let ZMPushStringMessageAdd = "add.message" // "[senderName]: [messageText]"
private let ZMPushStringImageAdd = "add.image" // "[senderName] shared a picture"
private let ZMPushStringVideoAdd = "add.video" // "[senderName] shared a video"
private let ZMPushStringAudioAdd = "add.audio" // "[senderName] shared an audio message"
private let ZMPushStringFileAdd = "add.file" // "[senderName] shared a file"
private let ZMPushStringLocationAdd = "add.location" // "[senderName] shared a location"
// currently disabled
// public let ZMPushStringMessageAddMany = "add.message.many" // "x new messages in [conversationName] / from [senderName]"
private let ZMPushStringFailedToSend = "failed.message" // "Unable to send a message"
private let ZMPushStringAlertAvailability = "alert.availability" // "Availability now affects notifications"
private let ZMPushStringMemberJoin = "member.join" // "[senderName] added you"
private let ZMPushStringMemberLeave = "member.leave" // "[senderName] removed you"
private let ZMPushStringMessageTimerUpdate = "message-timer.update" // "[senderName] set the message timer to [duration]
private let ZMPushStringMessageTimerOff = "message-timer.off" // "[senderName] turned off the message timer
private let ZMPushStringKnock = "knock" // "pinged"
private let ZMPushStringReaction = "reaction" // "[emoji] your message"
private let ZMPushStringVideoCallStarts = "call.started.video" // "is video calling"
private let ZMPushStringCallStarts = "call.started" // "is calling"
private let ZMPushStringCallMissed = "call.missed" // "called"
// currently disabled
// public let ZMPushStringCallMissedMany = "call.missed.many" // "You have x missed calls in a conversation"
private let ZMPushStringConnectionRequest = "connection.request" // "[senderName] wants to connect"
private let ZMPushStringConnectionAccepted = "connection.accepted" // "You and [senderName] are now connected"
private let ZMPushStringConversationCreate = "conversation.create" // "[senderName] created a group"
private let ZMPushStringConversationDelete = "conversation.delete" // "[senderName] deleted the group"
private let ZMPushStringNewConnection = "new_user" // "[senderName] just joined Wire"
private let OneOnOneKey = "oneonone"
private let GroupKey = "group"
private let SelfKey = "self"
private let MentionKey = "mention"
private let ReplyKey = "reply"
private let TeamKey = "team"
private let NoConversationNameKey = "noconversationname"
private let NoUserNameKey = "nousername"
extension LocalNotificationType {
fileprivate var baseKey: String {
switch self {
case .message(let contentType):
switch contentType {
case .image:
return ZMPushStringImageAdd
case .video:
return ZMPushStringVideoAdd
case .audio:
return ZMPushStringAudioAdd
case .location:
return ZMPushStringLocationAdd
case .fileUpload:
return ZMPushStringFileAdd
case .text:
return ZMPushStringMessageAdd
case .knock:
return ZMPushStringKnock
case .reaction:
return ZMPushStringReaction
case .ephemeral:
return ZMPushStringEphemeral
case .hidden:
return ZMPushStringDefault
case .participantsAdded:
return ZMPushStringMemberJoin
case .participantsRemoved:
return ZMPushStringMemberLeave
case .messageTimerUpdate(nil):
return ZMPushStringMessageTimerOff
case .messageTimerUpdate:
return ZMPushStringMessageTimerUpdate
}
case .calling(let callState):
switch callState {
case .incoming(video: true, shouldRing: _, degraded: _):
return ZMPushStringVideoCallStarts
case .incoming(video: false, shouldRing: _, degraded: _):
return ZMPushStringCallStarts
case .terminating, .none:
return ZMPushStringCallMissed
default:
return ZMPushStringDefault
}
case .event(let eventType):
switch eventType {
case .conversationCreated:
return ZMPushStringConversationCreate
case .conversationDeleted:
return ZMPushStringConversationDelete
case .connectionRequestPending:
return ZMPushStringConnectionRequest
case .connectionRequestAccepted:
return ZMPushStringConnectionAccepted
case .newConnection:
return ZMPushStringNewConnection
}
case .failedMessage:
return ZMPushStringFailedToSend
case .availabilityBehaviourChangeAlert:
return ZMPushStringAlertAvailability
}
}
fileprivate func senderKey(_ sender: ZMUser?, _ conversation: ZMConversation?) -> String? {
guard let sender = sender else { return NoUserNameKey }
if case .failedMessage = self {
return nil
} else if sender.name == nil || sender.name!.isEmpty {
return NoUserNameKey
}
return nil
}
fileprivate func conversationKey(_ conversation: ZMConversation?) -> String? {
if conversation?.conversationType != .oneOnOne && conversation?.meaningfulDisplayName == nil {
return NoConversationNameKey
}
return nil
}
fileprivate func messageBodyText(eventType: LocalNotificationEventType, senderName: String?) -> String {
let senderKey = senderName == nil ? NoUserNameKey : nil
let localizationKey = [baseKey, senderKey].compactMap { $0 }.joined(separator: ".")
var arguments: [CVarArg] = []
if let senderName = senderName {
arguments.append(senderName)
}
return .localizedStringWithFormat(localizationKey.pushFormatString, arguments: arguments)
}
func titleText(selfUser: ZMUser, conversation: ZMConversation? = nil) -> String? {
if case .message(let contentType) = self {
switch contentType {
case .ephemeral:
return .localizedStringWithFormat(ZMPushStringEphemeralTitle.pushFormatString)
case .hidden:
return nil
default:
break
}
}
let teamName = selfUser.team?.name
let conversationName = conversation?.meaningfulDisplayName
if let conversationName = conversationName, let teamName = teamName {
return .localizedStringWithFormat(ZMPushStringTitle.pushFormatString, arguments: [conversationName, teamName])
} else if let conversationName = conversationName {
return conversationName
} else if let teamName = teamName {
return teamName
}
return nil
}
func alertTitleText(team: Team?) -> String? {
guard case .availabilityBehaviourChangeAlert(let availability) = self, availability.isOne(of: .away, .busy) else { return nil }
let teamName = team?.name
let teamKey = teamName != nil ? TeamKey : nil
let availabilityKey = availability == .away ? "away" : "busy"
let localizationKey = [baseKey, availabilityKey, "title", teamKey].compactMap({ $0 }).joined(separator: ".")
return .localizedStringWithFormat(localizationKey.pushFormatString, arguments: [teamName].compactMap({ $0 }))
}
func alertMessageBodyText() -> String {
guard case .availabilityBehaviourChangeAlert(let availability) = self, availability.isOne(of: .away, .busy) else { return "" }
let availabilityKey = availability == .away ? "away" : "busy"
let localizationKey = [baseKey, availabilityKey, "message"].compactMap({ $0 }).joined(separator: ".")
return .localizedStringWithFormat(localizationKey.pushFormatString)
}
func messageBodyText(senderName: String?) -> String {
if case LocalNotificationType.event(let eventType) = self {
return messageBodyText(eventType: eventType, senderName: senderName)
} else {
return messageBodyText(sender: nil, conversation: nil)
}
}
func messageBodyText(sender: ZMUser?, conversation: ZMConversation?) -> String {
if case LocalNotificationType.event(let eventType) = self {
return messageBodyText(eventType: eventType, senderName: sender?.name)
}
let conversationName = conversation?.userDefinedName ?? ""
let senderName = sender?.name ?? ""
var senderKey = self.senderKey(sender, conversation)
var conversationTypeKey: String? = (conversation?.conversationType != .oneOnOne) ? GroupKey : OneOnOneKey
let conversationKey = self.conversationKey(conversation)
var arguments: [CVarArg] = []
if senderKey == nil, conversation?.conversationType != .oneOnOne {
// if the conversation is oneOnOne, then the sender name will be in the notification title
arguments.append(senderName)
}
var mentionOrReplyKey: String?
switch self {
case .message(let contentType):
switch contentType {
case let .text(content, isMention, isReply):
arguments.append(content)
mentionOrReplyKey = isMention ? MentionKey : (isReply ? ReplyKey : nil)
case .reaction(emoji: let emoji):
arguments.append(emoji)
case .knock:
arguments.append(NSNumber(value: 1))
case let .ephemeral(isMention, isReply):
mentionOrReplyKey = isMention ? MentionKey : (isReply ? ReplyKey : nil)
let key = [baseKey, mentionOrReplyKey].compactMap { $0 }.joined(separator: ".")
return .localizedStringWithFormat(key.pushFormatString)
case .hidden:
return .localizedStringWithFormat(baseKey.pushFormatString)
case .messageTimerUpdate(let timerString):
if let string = timerString {
arguments.append(string)
}
conversationTypeKey = nil
case .participantsAdded:
conversationTypeKey = nil // System messages don't follow the template and is missing the `group` suffix
senderKey = SelfKey
case .participantsRemoved(let reason):
conversationTypeKey = nil // System messages don't follow the template and is missing the `group` suffix
senderKey = SelfKey
// If there is a reason for removal, we should display a simple message "You were removed"
mentionOrReplyKey = reason.stringValue != nil ? NoUserNameKey : nil
default:
break
}
default: break
}
if conversationKey == nil, conversation?.conversationType != .oneOnOne {
arguments.append(conversationName)
}
let localizationKey = [baseKey, conversationTypeKey, senderKey, conversationKey, mentionOrReplyKey].compactMap({ $0 }).joined(separator: ".")
return .localizedStringWithFormat(localizationKey.pushFormatString, arguments: arguments)
}
}
extension String {
internal var pushFormatString: String {
return Bundle(for: ZMUserSession.self).localizedString(forKey: "push.notification.\(self)", value: "", table: "Push")
}
internal var pushActionString: String {
return Bundle(for: ZMUserSession.self).localizedString(forKey: "push.notification.action.\(self)", value: "", table: "Push")
}
static fileprivate func localizedStringWithFormat(_ format: String, arguments: [CVarArg]) -> String {
switch arguments.count {
case 1:
return String.localizedStringWithFormat(format, arguments[0])
case 2:
return String.localizedStringWithFormat(format, arguments[0], arguments[1])
case 3:
return String.localizedStringWithFormat(format, arguments[0], arguments[1], arguments[2])
case 4:
return String.localizedStringWithFormat(format, arguments[0], arguments[1], arguments[2], arguments[3])
default:
return NSLocalizedString(format, comment: "")
}
}
}
|
043bc377bb2f06f104bc92819721f4c2
| 41.458967 | 149 | 0.638342 | false | false | false | false |
WestlakeAPC/game-off-2016
|
refs/heads/master
|
external/Fiber2D/Fiber2D/platform/macos/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// Fiber2D
//
// Created by Andrey Volodin on 25.07.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
import Cocoa
import SwiftBGFX
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
var director: Director!
var renderer: Renderer!
func applicationDidFinishLaunching(_ aNotification: Notification) {
Setup.shared.contentScale = 2.0
//;2*[_view convertSizeToBacking:NSMakeSize(1, 1)].width;
Setup.shared.assetScale = Setup.shared.contentScale
Setup.shared.UIScale = 0.5
let rect: CGRect = CGRect(x: 0, y: 0, width: 1024, height: 768)
window = NSWindow(contentRect: rect, styleMask: [NSClosableWindowMask, NSResizableWindowMask, NSTitledWindowMask], backing: .buffered, defer: false, screen: NSScreen.main())
let view: MetalView = MetalView(frame: rect)
view.wantsBestResolutionOpenGLSurface = true
self.window.contentView = view
let locator = FileLocator.shared
locator.untaggedContentScale = 4
locator.searchPaths = [ Bundle.main.resourcePath!, Bundle.main.resourcePath! + "/Resources" ]
window.center()
window.makeFirstResponder(view)
window.makeKeyAndOrderFront(window)
var pd = PlatformData()
pd.nwh = UnsafeMutableRawPointer(Unmanaged.passRetained(view).toOpaque())
pd.context = UnsafeMutableRawPointer(Unmanaged.passRetained(view.device!).toOpaque())
bgfx.setPlatformData(pd)
bgfx.renderFrame()
bgfx.initialize(type: .metal)
bgfx.reset(width: 1024, height: 768, options: [.vsync, .flipAfterRender])
//bgfx.renderFrame()
self.window.acceptsMouseMovedEvents = true
let director: Director = view.director
// director = Director(view: self)
Director.pushCurrentDirector(director)
director.present(scene: MainScene(size: director.designSize))
//director.present(scene: ViewportScene(size: director.designSize))
Director.popCurrentDirector()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
|
d8afd49807fed63eb928fcdbd936836c
| 35.095238 | 181 | 0.664028 | false | false | false | false |
blitzagency/amigo-swift
|
refs/heads/master
|
Amigo/ThreadLocalEngineFactory.swift
|
mit
|
1
|
//
// ThreadLocalEngineFactory.swift
// Amigo
//
// Created by Adam Venturella on 7/22/15.
// Copyright © 2015 BLITZ. All rights reserved.
//
import Foundation
public protocol ThreadLocalEngineFactory: EngineFactory{
func createEngine() -> Engine
}
extension ThreadLocalEngineFactory{
func engineForCurrentThread() -> Engine? {
let dict = NSThread.currentThread().threadDictionary
let obj = dict["amigo.threadlocal.engine"] as? Engine
if let obj = obj{
return obj
} else {
return nil
}
}
func createEngineForCurrentThread() -> Engine {
let engine = createEngine()
let dict = NSThread.currentThread().threadDictionary
dict["amigo.threadlocal.engine"] = engine as? AnyObject
return engine
}
public func connect() -> Engine {
if let engine = engineForCurrentThread(){
return engine
} else {
return createEngineForCurrentThread()
}
}
}
|
1ca09e1a072b12aca7cda00503ff5ec3
| 22.627907 | 63 | 0.624016 | false | false | false | false |
Pluto-tv/jsonjam
|
refs/heads/master
|
Example/Pods/JSONHelper/JSONHelper/Extensions/Double.swift
|
mit
|
1
|
//
// Copyright © 2016 Baris Sencan. All rights reserved.
//
import Foundation
extension Double: Convertible {
public static func convertFromValue<T>(_ value: T?) throws -> Double? {
guard let value = value else { return nil }
if let doubleValue = value as? Double {
return doubleValue
} else if let stringValue = value as? String {
return Double(stringValue)
} else if let floatValue = value as? Float {
return Double(floatValue)
} else if let intValue = value as? Int {
return Double(intValue)
}
throw ConversionError.unsupportedType
}
}
|
81714476c92a29bff6dd017871a64b7d
| 24.083333 | 73 | 0.667774 | false | false | false | false |
Jnosh/swift
|
refs/heads/master
|
test/NameBinding/name_lookup.swift
|
apache-2.0
|
2
|
// RUN: %target-typecheck-verify-swift
class ThisBase1 {
init() { }
var baseInstanceVar: Int
var baseProp : Int {
get {
return 42
}
set {}
}
func baseFunc0() {}
func baseFunc1(_ a: Int) {}
subscript(i: Int) -> Double {
get {
return Double(i)
}
set {
baseInstanceVar = i
}
}
class var baseStaticVar: Int = 42 // expected-error {{class stored properties not supported}}
class var baseStaticProp: Int {
get {
return 42
}
set {}
}
class func baseStaticFunc0() {}
struct BaseNestedStruct {} // expected-note {{did you mean 'BaseNestedStruct'?}}
class BaseNestedClass {
init() { }
}
enum BaseNestedUnion {
case BaseUnionX(Int)
}
typealias BaseNestedTypealias = Int // expected-note {{did you mean 'BaseNestedTypealias'?}}
}
class ThisDerived1 : ThisBase1 {
override init() { super.init() }
var derivedInstanceVar: Int
var derivedProp : Int {
get {
return 42
}
set {}
}
func derivedFunc0() {}
func derivedFunc1(_ a: Int) {}
subscript(i: Double) -> Int {
get {
return Int(i)
}
set {
baseInstanceVar = Int(i)
}
}
class var derivedStaticVar: Int = 42// expected-error {{class stored properties not supported}}
class var derivedStaticProp: Int {
get {
return 42
}
set {}
}
class func derivedStaticFunc0() {}
struct DerivedNestedStruct {}
class DerivedNestedClass {
init() { }
}
enum DerivedNestedUnion { // expected-note {{did you mean 'DerivedNestedUnion'?}}
case DerivedUnionX(Int)
}
typealias DerivedNestedTypealias = Int
func testSelf1() {
self.baseInstanceVar = 42
self.baseProp = 42
self.baseFunc0()
self.baseFunc1(42)
self[0] = 42.0
self.baseStaticVar = 42 // expected-error {{static member 'baseStaticVar' cannot be used on instance of type 'ThisDerived1'}}
self.baseStaticProp = 42 // expected-error {{static member 'baseStaticProp' cannot be used on instance of type 'ThisDerived1'}}
self.baseStaticFunc0() // expected-error {{static member 'baseStaticFunc0' cannot be used on instance of type 'ThisDerived1'}}
self.baseExtProp = 42
self.baseExtFunc0()
self.baseExtStaticVar = 42
self.baseExtStaticProp = 42
self.baseExtStaticFunc0() // expected-error {{static member 'baseExtStaticFunc0' cannot be used on instance of type 'ThisDerived1'}}
var bs1 : BaseNestedStruct
var bc1 : BaseNestedClass
var bo1 : BaseNestedUnion = .BaseUnionX(42)
var bt1 : BaseNestedTypealias
var bs2 = self.BaseNestedStruct() // expected-error{{static member 'BaseNestedStruct' cannot be used on instance of type 'ThisDerived1'}}
var bc2 = self.BaseNestedClass() // expected-error{{static member 'BaseNestedClass' cannot be used on instance of type 'ThisDerived1'}}
var bo2 = self.BaseUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'BaseUnionX'}}
var bo3 = self.BaseNestedUnion.BaseUnionX(24) // expected-error{{static member 'BaseNestedUnion' cannot be used on instance of type 'ThisDerived1'}}
var bt2 = self.BaseNestedTypealias(42) // expected-error{{static member 'BaseNestedTypealias' cannot be used on instance of type 'ThisDerived1'}}
var bes1 : BaseExtNestedStruct
var bec1 : BaseExtNestedClass
var beo1 : BaseExtNestedUnion = .BaseExtUnionX(42)
var bet1 : BaseExtNestedTypealias
var bes2 = self.BaseExtNestedStruct() // expected-error{{static member 'BaseExtNestedStruct' cannot be used on instance of type 'ThisDerived1'}}
var bec2 = self.BaseExtNestedClass() // expected-error{{static member 'BaseExtNestedClass' cannot be used on instance of type 'ThisDerived1'}}
var beo2 = self.BaseExtUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'BaseExtUnionX'}}
var beo3 = self.BaseExtNestedUnion.BaseExtUnionX(24) // expected-error{{static member 'BaseExtNestedUnion' cannot be used on instance of type 'ThisDerived1'}}
var bet2 = self.BaseExtNestedTypealias(42) // expected-error{{static member 'BaseExtNestedTypealias' cannot be used on instance of type 'ThisDerived1'}}
self.derivedInstanceVar = 42
self.derivedProp = 42
self.derivedFunc0()
self.derivedStaticVar = 42 // expected-error {{static member 'derivedStaticVar' cannot be used on instance of type 'ThisDerived1'}}
self.derivedStaticProp = 42 // expected-error {{static member 'derivedStaticProp' cannot be used on instance of type 'ThisDerived1'}}
self.derivedStaticFunc0() // expected-error {{static member 'derivedStaticFunc0' cannot be used on instance of type 'ThisDerived1'}}
self.derivedExtProp = 42
self.derivedExtFunc0()
self.derivedExtStaticVar = 42
self.derivedExtStaticProp = 42
self.derivedExtStaticFunc0() // expected-error {{static member 'derivedExtStaticFunc0' cannot be used on instance of type 'ThisDerived1'}}
var ds1 : DerivedNestedStruct
var dc1 : DerivedNestedClass
var do1 : DerivedNestedUnion = .DerivedUnionX(42)
var dt1 : DerivedNestedTypealias
var ds2 = self.DerivedNestedStruct() // expected-error{{static member 'DerivedNestedStruct' cannot be used on instance of type 'ThisDerived1'}}
var dc2 = self.DerivedNestedClass() // expected-error{{static member 'DerivedNestedClass' cannot be used on instance of type 'ThisDerived1'}}
var do2 = self.DerivedUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'DerivedUnionX'}}
var do3 = self.DerivedNestedUnion.DerivedUnionX(24) // expected-error{{static member 'DerivedNestedUnion' cannot be used on instance of type 'ThisDerived1'}}
var dt2 = self.DerivedNestedTypealias(42) // expected-error{{static member 'DerivedNestedTypealias' cannot be used on instance of type 'ThisDerived1'}}
var des1 : DerivedExtNestedStruct
var dec1 : DerivedExtNestedClass
var deo1 : DerivedExtNestedUnion = .DerivedExtUnionX(42)
var det1 : DerivedExtNestedTypealias
var des2 = self.DerivedExtNestedStruct() // expected-error{{static member 'DerivedExtNestedStruct' cannot be used on instance of type 'ThisDerived1'}}
var dec2 = self.DerivedExtNestedClass() // expected-error{{static member 'DerivedExtNestedClass' cannot be used on instance of type 'ThisDerived1'}}
var deo2 = self.DerivedExtUnionX(24) // expected-error {{value of type 'ThisDerived1' has no member 'DerivedExtUnionX'}}
var deo3 = self.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error{{static member 'DerivedExtNestedUnion' cannot be used on instance of type 'ThisDerived1'}}
var det2 = self.DerivedExtNestedTypealias(42) // expected-error{{static member 'DerivedExtNestedTypealias' cannot be used on instance of type 'ThisDerived1'}}
self.Type // expected-error {{value of type 'ThisDerived1' has no member 'Type'}}
}
func testSuper1() {
super.baseInstanceVar = 42
super.baseProp = 42
super.baseFunc0()
super.baseFunc1(42)
super[0] = 42.0
super.baseStaticVar = 42 // expected-error {{static member 'baseStaticVar' cannot be used on instance of type 'ThisBase1'}}
super.baseStaticProp = 42 // expected-error {{static member 'baseStaticProp' cannot be used on instance of type 'ThisBase1'}}
super.baseStaticFunc0() // expected-error {{static member 'baseStaticFunc0' cannot be used on instance of type 'ThisBase1'}}
super.baseExtProp = 42
super.baseExtFunc0()
super.baseExtStaticVar = 42
super.baseExtStaticProp = 42
super.baseExtStaticFunc0() // expected-error {{static member 'baseExtStaticFunc0' cannot be used on instance of type 'ThisBase1'}}
var bs2 = super.BaseNestedStruct() // expected-error{{static member 'BaseNestedStruct' cannot be used on instance of type 'ThisBase1'}}
var bc2 = super.BaseNestedClass() // expected-error{{static member 'BaseNestedClass' cannot be used on instance of type 'ThisBase1'}}
var bo2 = super.BaseUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'BaseUnionX'}}
var bo3 = super.BaseNestedUnion.BaseUnionX(24) // expected-error{{static member 'BaseNestedUnion' cannot be used on instance of type 'ThisBase1'}}
var bt2 = super.BaseNestedTypealias(42) // expected-error{{static member 'BaseNestedTypealias' cannot be used on instance of type 'ThisBase1'}}
var bes2 = super.BaseExtNestedStruct() // expected-error{{static member 'BaseExtNestedStruct' cannot be used on instance of type 'ThisBase1'}}
var bec2 = super.BaseExtNestedClass() // expected-error{{static member 'BaseExtNestedClass' cannot be used on instance of type 'ThisBase1'}}
var beo2 = super.BaseExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'BaseExtUnionX'}}
var beo3 = super.BaseExtNestedUnion.BaseExtUnionX(24) // expected-error{{static member 'BaseExtNestedUnion' cannot be used on instance of type 'ThisBase1'}}
var bet2 = super.BaseExtNestedTypealias(42) // expected-error{{static member 'BaseExtNestedTypealias' cannot be used on instance of type 'ThisBase1'}}
super.derivedInstanceVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedInstanceVar'}}
super.derivedProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedProp'}}
super.derivedFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedFunc0'}}
super.derivedStaticVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticVar'}}
super.derivedStaticProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticProp'}}
super.derivedStaticFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedStaticFunc0'}}
super.derivedExtProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtProp'}}
super.derivedExtFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedExtFunc0'}}
super.derivedExtStaticVar = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticVar'}}
super.derivedExtStaticProp = 42 // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticProp'}}
super.derivedExtStaticFunc0() // expected-error {{value of type 'ThisBase1' has no member 'derivedExtStaticFunc0'}}
var ds2 = super.DerivedNestedStruct() // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedStruct'}}
var dc2 = super.DerivedNestedClass() // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedClass'}}
var do2 = super.DerivedUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedUnionX'}}
var do3 = super.DerivedNestedUnion.DerivedUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedUnion'}}
var dt2 = super.DerivedNestedTypealias(42) // expected-error {{value of type 'ThisBase1' has no member 'DerivedNestedTypealias'}}
var des2 = super.DerivedExtNestedStruct() // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedStruct'}}
var dec2 = super.DerivedExtNestedClass() // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedClass'}}
var deo2 = super.DerivedExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtUnionX'}}
var deo3 = super.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedUnion'}}
var det2 = super.DerivedExtNestedTypealias(42) // expected-error {{value of type 'ThisBase1' has no member 'DerivedExtNestedTypealias'}}
super.Type // expected-error {{value of type 'ThisBase1' has no member 'Type'}}
}
class func staticTestSelf1() {
self.baseInstanceVar = 42 // expected-error {{member 'baseInstanceVar' cannot be used on type 'ThisDerived1'}}
self.baseProp = 42 // expected-error {{member 'baseProp' cannot be used on type 'ThisDerived1'}}
self.baseFunc0() // expected-error {{instance member 'baseFunc0' cannot be used on type 'ThisDerived1'}}
self.baseFunc0(ThisBase1())() // expected-error {{'ThisBase1' is not convertible to 'ThisDerived1'}}
self.baseFunc0(ThisDerived1())()
self.baseFunc1(42) // expected-error {{instance member 'baseFunc1' cannot be used on type 'ThisDerived1'}}
self.baseFunc1(ThisBase1())(42) // expected-error {{'ThisBase1' is not convertible to 'ThisDerived1'}}
self.baseFunc1(ThisDerived1())(42)
self[0] = 42.0 // expected-error {{instance member 'subscript' cannot be used on type 'ThisDerived1'}}
self.baseStaticVar = 42
self.baseStaticProp = 42
self.baseStaticFunc0()
self.baseExtProp = 42 // expected-error {{member 'baseExtProp' cannot be used on type 'ThisDerived1'}}
self.baseExtFunc0() // expected-error {{instance member 'baseExtFunc0' cannot be used on type 'ThisDerived1'}}
self.baseExtStaticVar = 42
self.baseExtStaticProp = 42 // expected-error {{member 'baseExtStaticProp' cannot be used on type 'ThisDerived1'}}
self.baseExtStaticFunc0()
var bs1 : BaseNestedStruct
var bc1 : BaseNestedClass
var bo1 : BaseNestedUnion = .BaseUnionX(42)
var bt1 : BaseNestedTypealias
var bs2 = self.BaseNestedStruct()
var bc2 = self.BaseNestedClass()
var bo2 = self.BaseUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'BaseUnionX'}}
var bo3 = self.BaseNestedUnion.BaseUnionX(24)
var bt2 = self.BaseNestedTypealias()
self.derivedInstanceVar = 42 // expected-error {{member 'derivedInstanceVar' cannot be used on type 'ThisDerived1'}}
self.derivedProp = 42 // expected-error {{member 'derivedProp' cannot be used on type 'ThisDerived1'}}
self.derivedFunc0() // expected-error {{instance member 'derivedFunc0' cannot be used on type 'ThisDerived1'}}
self.derivedFunc0(ThisBase1())() // expected-error {{'ThisBase1' is not convertible to 'ThisDerived1'}}
self.derivedFunc0(ThisDerived1())()
self.derivedStaticVar = 42
self.derivedStaticProp = 42
self.derivedStaticFunc0()
self.derivedExtProp = 42 // expected-error {{member 'derivedExtProp' cannot be used on type 'ThisDerived1'}}
self.derivedExtFunc0() // expected-error {{instance member 'derivedExtFunc0' cannot be used on type 'ThisDerived1'}}
self.derivedExtStaticVar = 42
self.derivedExtStaticProp = 42 // expected-error {{member 'derivedExtStaticProp' cannot be used on type 'ThisDerived1'}}
self.derivedExtStaticFunc0()
var ds1 : DerivedNestedStruct
var dc1 : DerivedNestedClass
var do1 : DerivedNestedUnion = .DerivedUnionX(42)
var dt1 : DerivedNestedTypealias
var ds2 = self.DerivedNestedStruct()
var dc2 = self.DerivedNestedClass()
var do2 = self.DerivedUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'DerivedUnionX'}}
var do3 = self.DerivedNestedUnion.DerivedUnionX(24)
var dt2 = self.DerivedNestedTypealias()
var des1 : DerivedExtNestedStruct
var dec1 : DerivedExtNestedClass
var deo1 : DerivedExtNestedUnion = .DerivedExtUnionX(42)
var det1 : DerivedExtNestedTypealias
var des2 = self.DerivedExtNestedStruct()
var dec2 = self.DerivedExtNestedClass()
var deo2 = self.DerivedExtUnionX(24) // expected-error {{type 'ThisDerived1' has no member 'DerivedExtUnionX'}}
var deo3 = self.DerivedExtNestedUnion.DerivedExtUnionX(24)
var det2 = self.DerivedExtNestedTypealias()
self.Type // expected-error {{type 'ThisDerived1' has no member 'Type'}}
}
class func staticTestSuper1() {
super.baseInstanceVar = 42 // expected-error {{member 'baseInstanceVar' cannot be used on type 'ThisBase1'}}
super.baseProp = 42 // expected-error {{member 'baseProp' cannot be used on type 'ThisBase1'}}
super.baseFunc0() // expected-error {{instance member 'baseFunc0' cannot be used on type 'ThisBase1'}}
super.baseFunc0(ThisBase1())()
super.baseFunc1(42) // expected-error {{instance member 'baseFunc1' cannot be used on type 'ThisBase1'}}
super.baseFunc1(ThisBase1())(42)
super[0] = 42.0 // expected-error {{instance member 'subscript' cannot be used on type 'ThisBase1'}}
super.baseStaticVar = 42
super.baseStaticProp = 42
super.baseStaticFunc0()
super.baseExtProp = 42 // expected-error {{member 'baseExtProp' cannot be used on type 'ThisBase1'}}
super.baseExtFunc0() // expected-error {{instance member 'baseExtFunc0' cannot be used on type 'ThisBase1'}}
super.baseExtStaticVar = 42
super.baseExtStaticProp = 42 // expected-error {{member 'baseExtStaticProp' cannot be used on type 'ThisBase1'}}
super.baseExtStaticFunc0()
var bs2 = super.BaseNestedStruct()
var bc2 = super.BaseNestedClass()
var bo2 = super.BaseUnionX(24) // expected-error {{type 'ThisBase1' has no member 'BaseUnionX'}}
var bo3 = super.BaseNestedUnion.BaseUnionX(24)
var bt2 = super.BaseNestedTypealias()
super.derivedInstanceVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedInstanceVar'}}
super.derivedProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedProp'}}
super.derivedFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedFunc0'}}
super.derivedStaticVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedStaticVar'}}
super.derivedStaticProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedStaticProp'}}
super.derivedStaticFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedStaticFunc0'}}
super.derivedExtProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtProp'}}
super.derivedExtFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedExtFunc0'}}
super.derivedExtStaticVar = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticVar'}}
super.derivedExtStaticProp = 42 // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticProp'}}
super.derivedExtStaticFunc0() // expected-error {{type 'ThisBase1' has no member 'derivedExtStaticFunc0'}}
var ds2 = super.DerivedNestedStruct() // expected-error {{type 'ThisBase1' has no member 'DerivedNestedStruct'}}
var dc2 = super.DerivedNestedClass() // expected-error {{type 'ThisBase1' has no member 'DerivedNestedClass'}}
var do2 = super.DerivedUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedUnionX'}}
var do3 = super.DerivedNestedUnion.DerivedUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedNestedUnion'}}
var dt2 = super.DerivedNestedTypealias(42) // expected-error {{type 'ThisBase1' has no member 'DerivedNestedTypealias'}}
var des2 = super.DerivedExtNestedStruct() // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedStruct'}}
var dec2 = super.DerivedExtNestedClass() // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedClass'}}
var deo2 = super.DerivedExtUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedExtUnionX'}}
var deo3 = super.DerivedExtNestedUnion.DerivedExtUnionX(24) // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedUnion'}}
var det2 = super.DerivedExtNestedTypealias(42) // expected-error {{type 'ThisBase1' has no member 'DerivedExtNestedTypealias'}}
super.Type // expected-error {{type 'ThisBase1' has no member 'Type'}}
}
}
extension ThisBase1 {
var baseExtProp : Int {
get {
return 42
}
set {}
}
func baseExtFunc0() {}
var baseExtStaticVar: Int // expected-error {{extensions may not contain stored properties}} // expected-note 2 {{did you mean 'baseExtStaticVar'?}}
var baseExtStaticProp: Int { // expected-note 2 {{did you mean 'baseExtStaticProp'?}}
get {
return 42
}
set {}
}
class func baseExtStaticFunc0() {} // expected-note {{did you mean 'baseExtStaticFunc0'?}}
struct BaseExtNestedStruct {} // expected-note 2 {{did you mean 'BaseExtNestedStruct'?}}
class BaseExtNestedClass { // expected-note {{did you mean 'BaseExtNestedClass'?}}
init() { }
}
enum BaseExtNestedUnion { // expected-note {{did you mean 'BaseExtNestedUnion'?}}
case BaseExtUnionX(Int)
}
typealias BaseExtNestedTypealias = Int // expected-note 2 {{did you mean 'BaseExtNestedTypealias'?}}
}
extension ThisDerived1 {
var derivedExtProp : Int {
get {
return 42
}
set {}
}
func derivedExtFunc0() {}
var derivedExtStaticVar: Int // expected-error {{extensions may not contain stored properties}}
var derivedExtStaticProp: Int {
get {
return 42
}
set {}
}
class func derivedExtStaticFunc0() {}
struct DerivedExtNestedStruct {}
class DerivedExtNestedClass {
init() { }
}
enum DerivedExtNestedUnion { // expected-note {{did you mean 'DerivedExtNestedUnion'?}}
case DerivedExtUnionX(Int)
}
typealias DerivedExtNestedTypealias = Int
}
// <rdar://problem/11554141>
func shadowbug() {
var Foo = 10
func g() {
struct S {
var x : Foo
typealias Foo = Int
}
}
}
func scopebug() {
let Foo = 10
struct S {
typealias Foo = Int
}
_ = Foo
}
struct Ordering {
var x : Foo
typealias Foo = Int
}
// <rdar://problem/12202655>
class Outer {
class Inner {}
class MoreInner : Inner {}
}
func makeGenericStruct<S>(_ x: S) -> GenericStruct<S> {
return GenericStruct<S>()
}
struct GenericStruct<T> {}
// <rdar://problem/13952064>
extension Outer {
class ExtInner {}
}
// <rdar://problem/14149537>
func useProto<R : MyProto>(_ value: R) -> R.Element {
return value.get()
}
protocol MyProto {
associatedtype Element
func get() -> Element
}
// <rdar://problem/14488311>
struct DefaultArgumentFromExtension {
func g(_ x: @escaping (DefaultArgumentFromExtension) -> () -> () = f) {
let f = 42
var x2 = x
x2 = f // expected-error{{cannot assign value of type 'Int' to type '(DefaultArgumentFromExtension) -> () -> ()'}}
_ = x2
}
var x : (DefaultArgumentFromExtension) -> () -> () = f
}
extension DefaultArgumentFromExtension {
func f() {}
}
struct MyStruct {
var state : Bool
init() { state = true }
mutating func mod() {state = false}
// expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }}
func foo() { mod() } // expected-error {{cannot use mutating member on immutable value: 'self' is immutable}}
}
// <rdar://problem/19935319> QoI: poor diagnostic initializing a variable with a non-class func
class Test19935319 {
let i = getFoo() // expected-error {{cannot use instance member 'getFoo' within property initializer; property initializers run before 'self' is available}}
func getFoo() -> Int {}
}
class Test19935319G<T> {
let i = getFoo()
// expected-error@-1 {{cannot use instance member 'getFoo' within property initializer; property initializers run before 'self' is available}}
func getFoo() -> Int { return 42 }
}
// <rdar://problem/27013358> Crash using instance member as default parameter
class rdar27013358 {
let defaultValue = 1
func returnTwo() -> Int {
return 2
}
init(defaulted value: Int = defaultValue) {} // expected-error {{cannot use instance member 'defaultValue' as a default parameter}}
init(another value: Int = returnTwo()) {} // expected-error {{cannot use instance member 'returnTwo' as a default parameter}}
}
class rdar27013358G<T> {
let defaultValue = 1
func returnTwo() -> Int {
return 2
}
init(defaulted value: Int = defaultValue) {} // expected-error {{cannot use instance member 'defaultValue' as a default parameter}}
init(another value: Int = returnTwo()) {} // expected-error {{cannot use instance member 'returnTwo' as a default parameter}}
}
// <rdar://problem/23904262> QoI: ivar default initializer cannot reference other default initialized ivars?
class r23904262 {
let x = 1
let y = x // expected-error {{cannot use instance member 'x' within property initializer; property initializers run before 'self' is available}}
}
// <rdar://problem/21677702> Static method reference in static var doesn't work
class r21677702 {
static func method(value: Int) -> Int { return value }
static let x = method(value: 123)
static let y = method(123) // expected-error {{missing argument label 'value:' in call}}
}
// <rdar://problem/16954496> lazy properties must use "self." in their body, and can weirdly refer to class variables directly
class r16954496 {
func bar() {}
lazy var x: Array<() -> Void> = [bar]
}
// <rdar://problem/27413116> [Swift] Using static constant defined in enum when in switch statement doesn't compile
enum MyEnum {
case one
case two
case oneTwoThree
static let kMyConstant = "myConstant"
}
switch "someString" {
case MyEnum.kMyConstant: // this causes a compiler error
print("yay")
case MyEnum.self.kMyConstant: // this works fine
print("hmm")
default:
break
}
func foo() {
_ = MyEnum.One // expected-error {{enum type 'MyEnum' has no case 'One'; did you mean 'one'}}{{14-17=one}}
_ = MyEnum.Two // expected-error {{enum type 'MyEnum' has no case 'Two'; did you mean 'two'}}{{14-17=two}}
_ = MyEnum.OneTwoThree // expected-error {{enum type 'MyEnum' has no case 'OneTwoThree'; did you mean 'oneTwoThree'}}{{14-25=oneTwoThree}}
}
enum MyGenericEnum<T> {
case one(T)
case oneTwo(T)
}
func foo1() {
_ = MyGenericEnum<Int>.One // expected-error {{enum type 'MyGenericEnum<Int>' has no case 'One'; did you mean 'one'}}{{26-29=one}}
_ = MyGenericEnum<Int>.OneTwo // expected-error {{enum type 'MyGenericEnum<Int>' has no case 'OneTwo'; did you mean 'oneTwo'}}{{26-32=oneTwo}}
}
|
af6092b9e3a1abc0e667a6cd21f45782
| 44.09507 | 171 | 0.712423 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
refs/heads/develop
|
Carthage/Checkouts/swift-protobuf/Tests/SwiftProtobufTests/Test_AllTypes_Proto3.swift
|
apache-2.0
|
3
|
// Tests/SwiftProtobufTests/Test_AllTypes_Proto3.swift - Proto3 coding/decoding
//
// Copyright (c) 2014 - 2019 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Verify the binary coding/decoding for all field types in proto3. This
/// attempts to exercise both valid and invalid input, including error and
/// boundary cases. It also incidentally tests the type and names of generated
/// accessors.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
class Test_AllTypes_Proto3: XCTestCase, PBTestHelpers {
typealias MessageTestType = Proto3Unittest_TestAllTypes
// Custom decodeSucceeds that also does a round-trip through the Empty
// message to make sure unknown fields are consistently preserved by proto2.
func assertDecodeSucceeds(_ bytes: [UInt8], file: XCTestFileArgType = #file, line: UInt = #line, check: (MessageTestType) -> Bool) {
baseAssertDecodeSucceeds(bytes, file: file, line: line, check: check)
do {
// Make sure unknown fields are preserved by empty message decode/encode
let empty = try ProtobufUnittest_TestEmptyMessage(serializedBytes: bytes)
do {
let newBytes = try empty.serializedBytes()
XCTAssertEqual(bytes, newBytes, "Empty decode/recode did not match", file: file, line: line)
} catch let e {
XCTFail("Reserializing empty threw an error: \(e)", file: file, line: line)
}
} catch {
XCTFail("Empty decoding threw an error", file: file, line: line)
}
}
func assertDebugDescription(_ expected: String, file: XCTestFileArgType = #file, line: UInt = #line, configure: (inout MessageTestType) -> ()) {
var m = MessageTestType()
configure(&m)
let actual = m.debugDescription
XCTAssertEqual(actual, expected, file: file, line: line)
}
//
// Singular types
//
func testEncoding_optionalInt32() {
assertEncode([8, 1]) {(o: inout MessageTestType) in o.optionalInt32 = 1}
assertEncode([8, 255, 255, 255, 255, 7]) {(o: inout MessageTestType) in o.optionalInt32 = Int32.max}
assertEncode([8, 128, 128, 128, 128, 248, 255, 255, 255, 255, 1]) {(o: inout MessageTestType) in o.optionalInt32 = Int32.min}
assertDecodeSucceeds([8, 1]) {(o: MessageTestType) in
let t: Int32 = o.optionalInt32
return t == 1
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_int32: 1\n") {(o: inout MessageTestType) in o.optionalInt32 = 1}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_int32: -2147483648\noptional_uint32: 4294967295\n") {(o: inout MessageTestType) in
o.optionalInt32 = Int32.min
o.optionalUint32 = UInt32.max
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\n") {(o: inout MessageTestType) in
o.optionalInt32 = 1
o.optionalInt32 = 0
}
// Technically, this overflows Int32, but we truncate and accept it.
assertDecodeSucceeds([8, 255, 255, 255, 255, 255, 255, 1]) {$0.optionalInt32 == -1}
assertDecodeFails([8])
assertDecodeFails([9, 57]) // Cannot use wire type 1
assertDecodeFails([10, 58]) // Cannot use wire type 2
assertDecodeFails([11, 59]) // Cannot use wire type 3
assertDecodeFails([12, 60]) // Cannot use wire type 4
assertDecodeFails([13, 61]) // Cannot use wire type 5
assertDecodeFails([14, 62]) // Cannot use wire type 6
assertDecodeFails([15, 63]) // Cannot use wire type 7
assertDecodeFails([8, 188])
assertDecodeFails([8])
let empty = MessageTestType()
var a = empty
a.optionalInt32 = 0
XCTAssertEqual(a, empty)
var b = empty
b.optionalInt32 = 1
XCTAssertNotEqual(a, b)
b.optionalInt32 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalInt64() {
assertEncode([16, 1]) {(o: inout MessageTestType) in o.optionalInt64 = 1}
assertEncode([16, 255, 255, 255, 255, 255, 255, 255, 255, 127]) {(o: inout MessageTestType) in o.optionalInt64 = Int64.max}
assertEncode([16, 128, 128, 128, 128, 128, 128, 128, 128, 128, 1]) {(o: inout MessageTestType) in o.optionalInt64 = Int64.min}
assertDecodeSucceeds([16, 184, 156, 195, 145, 203, 1]) {(o: MessageTestType) in
let t: Int64 = o.optionalInt64 // Verify in-memory type
return t == 54529150520
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_int64: 1\n") {(o: inout MessageTestType) in o.optionalInt64 = 1}
assertDecodeFails([16])
assertDecodeFails([16, 184, 156, 195, 145, 203])
assertDecodeFails([17, 81])
assertDecodeFails([18, 82])
assertDecodeFails([19, 83])
assertDecodeFails([20, 84])
assertDecodeFails([21, 85])
assertDecodeFails([22, 86])
assertDecodeFails([23, 87])
let empty = MessageTestType()
var a = empty
a.optionalInt64 = 0
XCTAssertEqual(a, empty)
var b = empty
b.optionalInt64 = 1
XCTAssertNotEqual(a, b)
b.optionalInt64 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalUint32() {
assertEncode([24, 255, 255, 255, 255, 15]) {(o: inout MessageTestType) in o.optionalUint32 = UInt32.max}
assertDecodeSucceeds([24, 149, 88]) {(o: MessageTestType) in
let t: UInt32 = o.optionalUint32
return t == 11285
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_uint32: 1\n") {(o: inout MessageTestType) in o.optionalUint32 = 1}
assertDecodeFails([24])
assertDecodeFails([24, 149])
assertDecodeFails([25, 105])
assertDecodeFails([26, 106])
assertDecodeFails([27, 107])
assertDecodeFails([28, 108])
assertDecodeFails([29, 109])
assertDecodeFails([30, 110])
assertDecodeFails([31, 111])
let empty = MessageTestType()
var a = empty
a.optionalUint32 = 0
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalUint32 = 1
XCTAssertNotEqual(a, b)
b.optionalUint32 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalUint64() throws {
assertEncode([32, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]) {(o: inout MessageTestType) in o.optionalUint64 = UInt64.max}
assertDecodeSucceeds([32, 149, 7]) {(o: MessageTestType) in
let t: UInt64 = o.optionalUint64
return t == 917
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_uint64: 1\n") {(o: inout MessageTestType) in o.optionalUint64 = 1}
assertDecodeFails([32])
assertDecodeFails([32, 149])
assertDecodeFails([32, 149, 190, 193, 230, 186, 233, 166, 219])
assertDecodeFails([33])
assertDecodeFails([33, 0])
assertDecodeFails([33, 8, 0])
assertDecodeFails([34])
assertDecodesAsUnknownFields([34, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([34, 8, 0])
assertDecodeFails([35])
assertDecodeFails([35, 0])
assertDecodeFails([35, 8, 0])
assertDecodeFails([36])
assertDecodeFails([36, 0])
assertDecodeFails([36, 8, 0])
assertDecodeFails([37])
assertDecodeFails([37, 0])
assertDecodeFails([37, 8, 0])
assertDecodeFails([38])
assertDecodeFails([38, 0])
assertDecodeFails([38, 8, 0])
assertDecodeFails([39])
assertDecodeFails([39, 0])
assertDecodeFails([39, 8, 0])
let empty = MessageTestType()
var a = empty
a.optionalUint64 = 0
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalUint64 = 1
XCTAssertNotEqual(a, b)
b.optionalUint64 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalSint32() {
assertEncode([40, 254, 255, 255, 255, 15]) {(o: inout MessageTestType) in o.optionalSint32 = Int32.max}
assertEncode([40, 255, 255, 255, 255, 15]) {(o: inout MessageTestType) in o.optionalSint32 = Int32.min}
assertDecodeSucceeds([40, 0x81, 0x82, 0x80, 0x00]) {(o: MessageTestType) in
let t: Int32 = o.optionalSint32 // Verify in-memory type
return t == -129
}
assertDecodeSucceeds([40, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00]) {$0.optionalSint32 == 0}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_sint32: 1\n") {(o: inout MessageTestType) in o.optionalSint32 = 1}
// Truncate on overflow
assertDecodeSucceeds([40, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f]) {$0.optionalSint32 == -2147483648}
assertDecodeSucceeds([40, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x7f]) {$0.optionalSint32 == 2147483647}
assertDecodeFails([40])
assertDecodeFails([40, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00])
assertDecodeFails([41])
assertDecodeFails([41, 0])
assertDecodeFails([42])
assertDecodesAsUnknownFields([42, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([43])
assertDecodeFails([43, 0])
assertDecodeFails([44])
assertDecodeFails([44, 0])
assertDecodeFails([45])
assertDecodeFails([45, 0])
assertDecodeFails([46])
assertDecodeFails([46, 0])
assertDecodeFails([47])
assertDecodeFails([47, 0])
let empty = MessageTestType()
var a = empty
a.optionalSint32 = 0
XCTAssertEqual(a, empty)
var b = empty
b.optionalSint32 = 1
XCTAssertNotEqual(a, b)
b.optionalSint32 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalSint64() {
assertEncode([48, 254, 255, 255, 255, 255, 255, 255, 255, 255, 1]) {(o: inout MessageTestType) in o.optionalSint64 = Int64.max}
assertEncode([48, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]) {(o: inout MessageTestType) in o.optionalSint64 = Int64.min}
assertDecodeSucceeds([48, 139, 94]) {(o: MessageTestType) in
let t: Int64 = o.optionalSint64
return t == -6022
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_sint64: 1\n") {(o: inout MessageTestType) in o.optionalSint64 = 1}
assertDecodeFails([48])
assertDecodeFails([48, 139])
assertDecodeFails([49])
assertDecodeFails([49, 0])
assertDecodeFails([50])
assertDecodesAsUnknownFields([50, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([51])
assertDecodeFails([51, 0])
assertDecodeFails([52])
assertDecodeFails([52, 0])
assertDecodeFails([53])
assertDecodeFails([53, 0])
assertDecodeFails([54])
assertDecodeFails([54, 0])
assertDecodeFails([55])
assertDecodeFails([55, 0])
let empty = MessageTestType()
var a = empty
a.optionalSint64 = 0
XCTAssertEqual(a, empty)
var b = empty
b.optionalSint64 = 1
XCTAssertNotEqual(a, b)
b.optionalSint64 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalFixed32() throws {
assertEncode([61, 255, 255, 255, 255]) {(o: inout MessageTestType) in o.optionalFixed32 = UInt32.max}
assertDecodeSucceeds([61, 8, 12, 108, 1]) {(o: MessageTestType) in
let t: UInt32 = o.optionalFixed32
return t == 23858184
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_fixed32: 1\n") {(o: inout MessageTestType) in o.optionalFixed32 = 1}
assertDecodeFails([61])
assertDecodeFails([61, 255])
assertDecodeFails([61, 255, 255])
assertDecodeFails([61, 255, 255, 255])
assertDecodeFails([56])
assertDecodesAsUnknownFields([56, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([56, 0, 0, 0, 0])
assertDecodeFails([57])
assertDecodeFails([57, 0])
assertDecodeFails([57, 0, 0, 0, 0])
assertDecodeFails([58])
assertDecodesAsUnknownFields([58, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([58, 0, 0, 0, 0])
assertDecodeFails([59])
assertDecodeFails([59, 0])
assertDecodeFails([59, 0, 0, 0, 0])
assertDecodeFails([60])
assertDecodeFails([60, 0])
assertDecodeFails([60, 0, 0, 0, 0])
assertDecodeFails([62])
assertDecodeFails([62, 0])
assertDecodeFails([62, 0, 0, 0, 0])
assertDecodeFails([63])
assertDecodeFails([63, 0])
assertDecodeFails([63, 0, 0, 0, 0])
let empty = MessageTestType()
var a = empty
a.optionalFixed32 = 0
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalFixed32 = 1
XCTAssertNotEqual(a, b)
b.optionalFixed32 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalFixed64() throws {
assertEncode([65, 255, 255, 255, 255, 255, 255, 255, 255]) {(o: inout MessageTestType) in o.optionalFixed64 = UInt64.max}
assertDecodeSucceeds([65, 255, 255, 255, 255, 255, 255, 255, 255]) {(o: MessageTestType) in
let t: UInt64 = o.optionalFixed64 // Verify in-memory type
return t == 18446744073709551615
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_fixed64: 1\n") {(o: inout MessageTestType) in o.optionalFixed64 = 1}
assertDecodeFails([65])
assertDecodeFails([65, 255])
assertDecodeFails([65, 255, 255])
assertDecodeFails([65, 255, 255, 255])
assertDecodeFails([65, 255, 255, 255, 255])
assertDecodeFails([65, 255, 255, 255, 255, 255])
assertDecodeFails([65, 255, 255, 255, 255, 255, 255])
assertDecodeFails([65, 255, 255, 255, 255, 255, 255, 255])
assertDecodeFails([64])
assertDecodesAsUnknownFields([64, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([64, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([66])
assertDecodesAsUnknownFields([66, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([66, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([67])
assertDecodeFails([67, 0])
assertDecodeFails([67, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([68])
assertDecodeFails([68, 0])
assertDecodeFails([68, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([69])
assertDecodeFails([69, 0])
assertDecodeFails([69, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([69])
assertDecodeFails([69, 0])
assertDecodeFails([70, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([71])
assertDecodeFails([71, 0])
assertDecodeFails([71, 0, 0, 0, 0, 0, 0, 0, 0])
let empty = MessageTestType()
var a = empty
a.optionalFixed64 = 0
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalFixed64 = 1
XCTAssertNotEqual(a, b)
b.optionalFixed64 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalSfixed32() throws {
assertEncode([77, 255, 255, 255, 127]) {(o: inout MessageTestType) in o.optionalSfixed32 = Int32.max}
assertEncode([77, 0, 0, 0, 128]) {(o: inout MessageTestType) in o.optionalSfixed32 = Int32.min}
assertDecodeSucceeds([77, 0, 0, 0, 0]) {(o: MessageTestType) in
let t: Int32 = o.optionalSfixed32 // Verify in-memory type
return t == 0
}
assertDecodeSucceeds([77, 255, 255, 255, 255]) {$0.optionalSfixed32 == -1}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_sfixed32: 1\n") {(o: inout MessageTestType) in o.optionalSfixed32 = 1}
assertDecodeFails([77])
assertDecodeFails([77])
assertDecodeFails([77, 0])
assertDecodeFails([77, 0, 0])
assertDecodeFails([77, 0, 0, 0])
assertDecodeFails([72])
assertDecodesAsUnknownFields([72, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([72, 0, 0, 0, 0])
assertDecodeFails([73])
assertDecodeFails([73, 0])
assertDecodeFails([73, 0, 0, 0, 0])
assertDecodeFails([74])
assertDecodesAsUnknownFields([74, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([74, 0, 0, 0, 0])
assertDecodeFails([75])
assertDecodeFails([75, 0])
assertDecodeFails([75, 0, 0, 0, 0])
assertDecodeFails([76])
assertDecodeFails([76, 0])
assertDecodeFails([76, 0, 0, 0, 0])
assertDecodeFails([78])
assertDecodeFails([78, 0])
assertDecodeFails([78, 0, 0, 0, 0])
assertDecodeFails([79])
assertDecodeFails([79, 0])
assertDecodeFails([79, 0, 0, 0, 0])
let empty = MessageTestType()
var a = empty
a.optionalSfixed32 = 0
XCTAssertEqual(a, empty)
var b = empty
b.optionalSfixed32 = 1
XCTAssertNotEqual(a, b)
b.optionalSfixed32 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalSfixed64() throws {
assertEncode([81, 255, 255, 255, 255, 255, 255, 255, 127]) {(o: inout MessageTestType) in o.optionalSfixed64 = Int64.max}
assertEncode([81, 0, 0, 0, 0, 0, 0, 0, 128]) {(o: inout MessageTestType) in o.optionalSfixed64 = Int64.min}
assertDecodeSucceeds([81, 0, 0, 0, 0, 0, 0, 0, 128]) {(o: MessageTestType) in
let t: Int64 = o.optionalSfixed64 // Verify in-memory type
return t == -9223372036854775808
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_sfixed64: 1\n") {(o: inout MessageTestType) in o.optionalSfixed64 = 1}
assertDecodeFails([81])
assertDecodeFails([81, 0])
assertDecodeFails([81, 0, 0])
assertDecodeFails([81, 0, 0, 0])
assertDecodeFails([81, 0, 0, 0, 0])
assertDecodeFails([81, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([80])
assertDecodesAsUnknownFields([80, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([80, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([82])
assertDecodesAsUnknownFields([82, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([82, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([83])
assertDecodeFails([83, 0])
assertDecodeFails([83, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([84])
assertDecodeFails([84, 0])
assertDecodeFails([84, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([85])
assertDecodeFails([85, 0])
assertDecodeFails([85, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([86])
assertDecodeFails([86, 0])
assertDecodeFails([86, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([87])
assertDecodeFails([87, 0])
assertDecodeFails([87, 0, 0, 0, 0, 0, 0, 0, 0])
let empty = MessageTestType()
var a = empty
a.optionalSfixed64 = 0
XCTAssertEqual(a, empty)
var b = empty
b.optionalSfixed64 = 1
XCTAssertNotEqual(a, b)
b.optionalSfixed64 = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalFloat() throws {
assertEncode([93, 0, 0, 0, 63]) {(o: inout MessageTestType) in o.optionalFloat = 0.5}
assertEncode([93, 0, 0, 0, 64]) {(o: inout MessageTestType) in o.optionalFloat = 2.0}
assertDecodeSucceeds([93, 0, 0, 0, 0]) {(o: MessageTestType) in
let t: Float = o.optionalFloat
return t == 0
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_float: 1.0\n") {
(o: inout MessageTestType) in o.optionalFloat = 1.0}
assertDecodeFails([93, 0, 0, 0])
assertDecodeFails([93, 0, 0])
assertDecodeFails([93, 0])
assertDecodeFails([93])
assertDecodeFails([88]) // Float cannot use wire type 0
assertDecodesAsUnknownFields([88, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([89]) // Float cannot use wire type 1
assertDecodeFails([89, 0, 0, 0, 0]) // Float cannot use wire type 1
assertDecodeFails([90]) // Float cannot use wire type 2
assertDecodesAsUnknownFields([90, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([91]) // Float cannot use wire type 3
assertDecodeFails([91, 0, 0, 0, 0]) // Float cannot use wire type 3
assertDecodeFails([92]) // Float cannot use wire type 4
assertDecodeFails([92, 0, 0, 0, 0]) // Float cannot use wire type 4
assertDecodeFails([94]) // Float cannot use wire type 6
assertDecodeFails([94, 0, 0, 0, 0]) // Float cannot use wire type 6
assertDecodeFails([95]) // Float cannot use wire type 7
assertDecodeFails([95, 0, 0, 0, 0]) // Float cannot use wire type 7
let empty = MessageTestType()
var a = empty
a.optionalFloat = 0
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalFloat = 1
XCTAssertNotEqual(a, b)
b.optionalFloat = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalDouble() throws {
assertEncode([97, 0, 0, 0, 0, 0, 0, 224, 63]) {(o: inout MessageTestType) in o.optionalDouble = 0.5}
assertEncode([97, 0, 0, 0, 0, 0, 0, 0, 64]) {(o: inout MessageTestType) in o.optionalDouble = 2.0}
assertDecodeSucceeds([97, 0, 0, 0, 0, 0, 0, 224, 63]) {(o: MessageTestType) in
let t: Double = o.optionalDouble
return t == 0.5
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_double: 1.0\n") {
(o: inout MessageTestType) in o.optionalDouble = 1.0}
assertDecodeFails([97, 0, 0, 0, 0, 0, 0, 224])
assertDecodeFails([97])
assertDecodeFails([96])
assertDecodesAsUnknownFields([96, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([96, 10, 10, 10, 10, 10, 10, 10, 10])
assertDecodeFails([98])
assertDecodesAsUnknownFields([98, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([98, 10, 10, 10, 10, 10, 10, 10, 10])
assertDecodeFails([99])
assertDecodeFails([99, 0])
assertDecodeFails([99, 10, 10, 10, 10, 10, 10, 10, 10])
assertDecodeFails([100])
assertDecodeFails([100, 0])
assertDecodeFails([100, 10, 10, 10, 10, 10, 10, 10, 10])
assertDecodeFails([101])
assertDecodeFails([101, 0])
assertDecodeFails([101, 10, 10, 10, 10, 10, 10, 10, 10])
assertDecodeFails([101])
assertDecodeFails([102, 0])
assertDecodeFails([102, 10, 10, 10, 10, 10, 10, 10, 10])
assertDecodeFails([103])
assertDecodeFails([103, 0])
assertDecodeFails([103, 10, 10, 10, 10, 10, 10, 10, 10])
let empty = MessageTestType()
var a = empty
a.optionalDouble = 0
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalDouble = 1
XCTAssertNotEqual(a, b)
b.optionalDouble = 0
XCTAssertEqual(a, b)
}
func testEncoding_optionalBool() throws {
assertEncode([104, 1]) {(o: inout MessageTestType) in o.optionalBool = true}
assertDecodeSucceeds([104, 1]) {(o: MessageTestType) in
let t: Bool = o.optionalBool // Verify non-optional
return t == true
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_bool: true\n") {(o: inout MessageTestType) in o.optionalBool = true}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\n") {(o: inout MessageTestType) in o.optionalBool = false}
assertDecodeFails([104])
assertDecodeFails([104, 255])
assertDecodeFails([105])
assertDecodeFails([105, 0])
assertDecodeFails([106])
assertDecodesAsUnknownFields([106, 0]) // Wrong wire type (length delimited), valid as an unknown field
assertDecodeFails([107])
assertDecodeFails([107, 0])
assertDecodeFails([108])
assertDecodeFails([108, 0])
assertDecodeFails([109])
assertDecodeFails([109, 0])
assertDecodeFails([110])
assertDecodeFails([110, 0])
assertDecodeFails([111])
assertDecodeFails([111, 0])
let empty = MessageTestType()
var a = empty
a.optionalBool = false
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalBool = true
XCTAssertNotEqual(a, b)
b.optionalBool = false
XCTAssertEqual(a, b)
}
func testEncoding_optionalString() throws {
assertEncode([114, 1, 65]) {(o: inout MessageTestType) in o.optionalString = "A"}
assertEncode([114, 4, 0xf0, 0x9f, 0x98, 0x84]) {(o: inout MessageTestType) in o.optionalString = "😄"}
assertDecodeSucceeds([114, 5, 72, 101, 108, 108, 111]) {(o: MessageTestType) in
let t: String = o.optionalString // Verify non-optional
return t == "Hello"
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_string: \"abc\"\n") {(o: inout MessageTestType) in o.optionalString = "abc"}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_string: \"\\b\\t\"\n") {(o: inout MessageTestType) in o.optionalString = "\u{08}\u{09}"}
assertDecodeFails([114])
assertDecodeFails([114, 1])
assertDecodeFails([114, 2, 65])
assertDecodeFails([114, 1, 193]) // Invalid UTF-8
assertDecodeFails([112])
assertDecodesAsUnknownFields([112, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([113])
assertDecodeFails([113, 0])
assertDecodeFails([115])
assertDecodeFails([115, 0])
assertDecodeFails([116])
assertDecodeFails([116, 0])
assertDecodeFails([117])
assertDecodeFails([117, 0])
assertDecodeFails([118])
assertDecodeFails([118, 0])
assertDecodeFails([119])
assertDecodeFails([119, 0])
let empty = MessageTestType()
var a = empty
a.optionalString = ""
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalString = "a"
XCTAssertNotEqual(a, b)
b.optionalString = ""
XCTAssertEqual(a, b)
}
func testEncoding_optionalBytes() {
assertEncode([122, 1, 1]) {(o: inout MessageTestType) in o.optionalBytes = Data([1])}
assertEncode([122, 2, 1, 2]) {(o: inout MessageTestType) in o.optionalBytes = Data([1, 2])}
assertDecodeSucceeds([122, 4, 0, 1, 2, 255]) {(o: MessageTestType) in
let t = o.optionalBytes // Verify non-optional
return t == Data([0, 1, 2, 255])
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_bytes: \"\\001\\002\\003\"\n") {(o: inout MessageTestType) in o.optionalBytes = Data([1, 2, 3])}
assertDecodeFails([122])
assertDecodeFails([122, 1])
assertDecodeFails([122, 2, 0])
assertDecodeFails([122, 3, 0, 0])
assertDecodeFails([120])
assertDecodesAsUnknownFields([120, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([121])
assertDecodeFails([121, 0])
assertDecodeFails([123])
assertDecodeFails([123, 0])
assertDecodeFails([124])
assertDecodeFails([124, 0])
assertDecodeFails([125])
assertDecodeFails([125, 0])
assertDecodeFails([126])
assertDecodeFails([126, 0])
assertDecodeFails([127])
assertDecodeFails([127, 0])
let empty = MessageTestType()
var a = empty
a.optionalBytes = Data()
XCTAssertEqual(a, empty)
XCTAssertEqual(try a.serializedBytes(), [])
var b = empty
b.optionalBytes = Data([1])
XCTAssertNotEqual(a, b)
b.optionalBytes = Data()
XCTAssertEqual(a, b)
}
func testEncoding_optionalNestedMessage() {
assertEncode([146, 1, 2, 8, 1]) {(o: inout MessageTestType) in
o.optionalNestedMessage.bb = 1
}
assertDecodeSucceeds([146, 1, 4, 8, 1, 8, 3]) {$0.optionalNestedMessage.bb == 3}
assertDecodeSucceeds([146, 1, 2, 8, 1, 146, 1, 2, 8, 4]) {$0.optionalNestedMessage.bb == 4}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_nested_message {\n bb: 1\n}\n") {(o: inout MessageTestType) in
var nested = MessageTestType.NestedMessage()
nested.bb = 1
o.optionalNestedMessage = nested
}
assertDecodeFails([146, 1, 2, 8, 128])
assertDecodeFails([146, 1, 1, 128])
let c = MessageTestType.with {
$0.optionalNestedMessage.bb = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalNestedMessage)
XCTAssertTrue(d.hasOptionalNestedMessage)
d.clearOptionalNestedMessage()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalNestedMessage)
XCTAssertFalse(d.hasOptionalNestedMessage)
}
func testEncoding_optionalForeignMessage() {
assertEncode([154, 1, 2, 8, 1]) {(o: inout MessageTestType) in
o.optionalForeignMessage.c = 1
}
assertDecodeSucceeds([154, 1, 4, 8, 1, 8, 3]) {$0.optionalForeignMessage.c == 3}
assertDecodeSucceeds([154, 1, 2, 8, 1, 154, 1, 2, 8, 4]) {$0.optionalForeignMessage.c == 4}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_foreign_message {\n c: 1\n}\n") {(o: inout MessageTestType) in
var foreign = Proto3Unittest_ForeignMessage()
foreign.c = 1
o.optionalForeignMessage = foreign
}
assertDecodesAsUnknownFields([152, 1, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([153, 1]) // Wire type 1
assertDecodeFails([153, 1, 0])
assertDecodesAsUnknownFields([153, 1, 0, 0, 0, 0, 0, 0, 0, 0]) // Wrong wire type (fixed64), valid as an unknown field
assertDecodeFails([155, 1]) // Wire type 3
assertDecodeFails([155, 1, 0])
assertDecodesAsUnknownFields([155, 1, 156, 1]) // Wrong wire type (start group, end group), valid as an unknown field
assertDecodeFails([156, 1]) // Wire type 4
assertDecodeFails([156, 1, 0])
assertDecodeFails([157, 1]) // Wire type 5
assertDecodeFails([157, 1, 0])
assertDecodesAsUnknownFields([157, 1, 0, 0, 0, 0]) // Wrong wire type (fixed32), valid as an unknown field
assertDecodeFails([158, 1]) // Wire type 6
assertDecodeFails([158, 1, 0])
assertDecodeFails([159, 1]) // Wire type 7
assertDecodeFails([159, 1, 0])
assertDecodeFails([154, 1, 4, 8, 1]) // Truncated
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalForeignMessage.c = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalForeignMessage)
XCTAssertTrue(d.hasOptionalForeignMessage)
d.clearOptionalForeignMessage()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalForeignMessage)
XCTAssertFalse(d.hasOptionalForeignMessage)
}
func testEncoding_optionalImportMessage() {
assertEncode([162, 1, 2, 8, 1]) {(o: inout MessageTestType) in
o.optionalImportMessage.d = 1
}
assertDecodeSucceeds([162, 1, 4, 8, 1, 8, 3]) {$0.optionalImportMessage.d == 3}
assertDecodeSucceeds([162, 1, 2, 8, 1, 162, 1, 2, 8, 4]) {$0.optionalImportMessage.d == 4}
// Ensure storage is uniqued for clear.
let c = MessageTestType.with {
$0.optionalImportMessage.d = 1
}
var d = c
XCTAssertEqual(c, d)
XCTAssertTrue(c.hasOptionalImportMessage)
XCTAssertTrue(d.hasOptionalImportMessage)
d.clearOptionalImportMessage()
XCTAssertNotEqual(c, d)
XCTAssertTrue(c.hasOptionalImportMessage)
XCTAssertFalse(d.hasOptionalImportMessage)
}
func testEncoding_optionalNestedEnum() {
assertEncode([168, 1, 2]) {(o: inout MessageTestType) in
o.optionalNestedEnum = .bar
}
assertDecodeSucceeds([168, 1, 2]) {$0.optionalNestedEnum == .bar}
assertDecodeFails([168, 1])
assertDecodeSucceeds([168, 1, 128, 1]) {$0.optionalNestedEnum == .UNRECOGNIZED(128)}
assertDecodeSucceeds([168, 1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]) {$0.optionalNestedEnum == .UNRECOGNIZED(-1)}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_nested_enum: BAR\n") {(o: inout MessageTestType) in
o.optionalNestedEnum = .bar
}
}
func testEncoding_optionalForeignEnum() {
assertEncode([176, 1, 5]) {(o: inout MessageTestType) in
o.optionalForeignEnum = .foreignBar
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_foreign_enum: FOREIGN_BAR\n") {(o: inout MessageTestType) in
o.optionalForeignEnum = .foreignBar
}
}
//
// Repeated types
//
func testEncoding_repeatedInt32() {
assertEncode([250, 1, 15, 255, 255, 255, 255, 7, 128, 128, 128, 128, 248, 255, 255, 255, 255, 1]) {(o: inout MessageTestType) in o.repeatedInt32 = [Int32.max, Int32.min]}
assertDecodeSucceeds([248, 1, 8, 248, 1, 247, 255, 255, 255, 15]) {$0.repeatedInt32 == [8, -9]}
assertDecodeFails([248, 1, 8, 248, 1, 247, 255, 255, 255, 255, 255, 255, 255, 255])
assertDecodeFails([248, 1, 8, 248, 1])
assertDecodeFails([248, 1])
assertDecodeFails([249, 1, 73])
// 250, 1 should actually work because that's packed
assertDecodeSucceeds([250, 1, 4, 8, 9, 10, 11]) {$0.repeatedInt32 == [8, 9, 10, 11]}
assertDecodeFails([251, 1, 75])
assertDecodeFails([252, 1, 76])
assertDecodeFails([253, 1, 77])
assertDecodeFails([254, 1, 78])
assertDecodeFails([255, 1, 79])
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\nrepeated_int32: [1]\n") {(o: inout MessageTestType) in
o.repeatedInt32 = [1]
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\n") {(o: inout MessageTestType) in
o.repeatedInt32 = []
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\nrepeated_int32: [1, 2]\n") {(o: inout MessageTestType) in
o.repeatedInt32 = [1, 2]
}
}
func testEncoding_repeatedInt64() {
assertEncode([130, 2, 19, 255, 255, 255, 255, 255, 255, 255, 255, 127, 128, 128, 128, 128, 128, 128, 128, 128, 128, 1]) {(o: inout MessageTestType) in o.repeatedInt64 = [Int64.max, Int64.min]}
assertDecodeSucceeds([128, 2, 255, 255, 153, 166, 234, 175, 227, 1, 128, 2, 185, 156, 196, 237, 158, 222, 230, 255, 255, 1]) {$0.repeatedInt64 == [999999999999999, -111111111111111]}
assertDecodeSucceeds([130, 2, 1, 1]) {$0.repeatedInt64 == [1]} // Accepts packed coding
assertDecodeFails([128, 2, 255, 255, 153, 166, 234, 175, 227, 1, 128, 2, 185, 156, 196, 237, 158, 222, 230, 255, 255])
assertDecodeFails([128, 2, 1, 128, 2])
assertDecodeFails([128, 2, 128])
assertDecodeFails([128, 2])
assertDecodeFails([129, 2, 97])
assertDecodeFails([131, 2, 99])
assertDecodeFails([132, 2, 100])
assertDecodeFails([133, 2, 101])
assertDecodeFails([134, 2, 102])
assertDecodeFails([135, 2, 103])
}
func testEncoding_repeatedUint32() {
assertEncode([138, 2, 6, 255, 255, 255, 255, 15, 0]) {(o: inout MessageTestType) in o.repeatedUint32 = [UInt32.max, UInt32.min]}
assertDecodeSucceeds([136, 2, 210, 9, 136, 2, 213, 27]) {(o:MessageTestType) in
o.repeatedUint32 == [1234, 3541]}
assertDecodeSucceeds([136, 2, 255, 255, 255, 255, 15, 136, 2, 213, 27]) {(o:MessageTestType) in
o.repeatedUint32 == [4294967295, 3541]}
assertDecodeSucceeds([138, 2, 2, 1, 2]) {(o:MessageTestType) in
o.repeatedUint32 == [1, 2]}
// Truncate on 32-bit overflow
assertDecodeSucceeds([136, 2, 255, 255, 255, 255, 31]) {(o:MessageTestType) in
o.repeatedUint32 == [4294967295]}
assertDecodeSucceeds([136, 2, 255, 255, 255, 255, 255, 255, 255, 1]) {(o:MessageTestType) in
o.repeatedUint32 == [4294967295]}
assertDecodeFails([136, 2])
assertDecodeFails([136, 2, 210])
assertDecodeFails([136, 2, 210, 9, 120, 213])
assertDecodeFails([137, 2, 121])
assertDecodeFails([139, 2, 123])
assertDecodeFails([140, 2, 124])
assertDecodeFails([141, 2, 125])
assertDecodeFails([142, 2, 126])
assertDecodeFails([143, 2, 127])
}
func testEncoding_repeatedUint64() {
assertEncode([146, 2, 11, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1, 0]) {(o: inout MessageTestType) in o.repeatedUint64 = [UInt64.max, UInt64.min]}
assertDecodeSucceeds([144, 2, 149, 8]) {$0.repeatedUint64 == [1045 ]}
assertDecodeSucceeds([146, 2, 2, 0, 1]) {$0.repeatedUint64 == [0, 1]}
assertDecodeFails([144])
assertDecodeFails([144, 2])
assertDecodeFails([144, 2, 149])
assertDecodeFails([144, 2, 149, 154, 239, 255, 255, 255, 255, 255, 255, 255])
assertDecodeFails([145, 2])
assertDecodeFails([145, 2, 0])
assertDecodeFails([147, 2])
assertDecodeFails([147, 2, 0])
assertDecodeFails([148, 2])
assertDecodeFails([148, 2, 0])
assertDecodeFails([149, 2])
assertDecodeFails([149, 2, 0])
assertDecodeFails([150, 2])
assertDecodeFails([150, 2, 0])
assertDecodeFails([151, 2])
assertDecodeFails([151, 2, 0])
}
func testEncoding_repeatedSint32() {
assertEncode([154, 2, 10, 254, 255, 255, 255, 15, 255, 255, 255, 255, 15]) {(o: inout MessageTestType) in o.repeatedSint32 = [Int32.max, Int32.min]}
assertDecodeSucceeds([152, 2, 170, 180, 222, 117, 152, 2, 225, 162, 243, 173, 1]) {$0.repeatedSint32 == [123456789, -182347953]}
assertDecodeSucceeds([154, 2, 1, 0]) {$0.repeatedSint32 == [0]}
assertDecodeSucceeds([154, 2, 1, 1, 152, 2, 2]) {$0.repeatedSint32 == [-1, 1]}
// 32-bit overflow truncates
assertDecodeSucceeds([152, 2, 170, 180, 222, 117, 152, 2, 225, 162, 243, 173, 255, 255, 1]) {$0.repeatedSint32 == [123456789, -2061396145]}
assertDecodeFails([152, 2, 170, 180, 222, 117, 152])
assertDecodeFails([152, 2, 170, 180, 222, 117, 152, 2])
assertDecodeFails([152, 2, 170, 180, 222, 117, 152, 2, 225])
assertDecodeFails([152, 2, 170, 180, 222, 117, 152, 2, 225, 162, 243, 173, 255, 255, 255, 255, 255, 255, 1])
assertDecodeFails([153, 2])
assertDecodeFails([153, 2, 0])
assertDecodeFails([155, 2])
assertDecodeFails([155, 2, 0])
assertDecodeFails([156, 2])
assertDecodeFails([156, 2, 0])
assertDecodeFails([157, 2])
assertDecodeFails([157, 2, 0])
assertDecodeFails([158, 2])
assertDecodeFails([158, 2, 0])
assertDecodeFails([159, 2])
assertDecodeFails([159, 2, 0])
}
func testEncoding_repeatedSint64() {
assertEncode([162, 2, 20, 254, 255, 255, 255, 255, 255, 255, 255, 255, 1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 1]) {(o: inout MessageTestType) in o.repeatedSint64 = [Int64.max, Int64.min]}
assertDecodeSucceeds([160, 2, 170, 180, 222, 117, 160, 2, 225, 162, 243, 173, 255, 89]) {$0.repeatedSint64 == [123456789,-1546102139057]}
assertDecodeSucceeds([162, 2, 1, 1]) {$0.repeatedSint64 == [-1]}
assertDecodeFails([160, 2, 170, 180, 222, 117, 160])
assertDecodeFails([160, 2, 170, 180, 222, 117, 160, 2])
assertDecodeFails([160, 2, 170, 180, 222, 117, 160, 2, 225])
assertDecodeFails([160, 2, 170, 180, 222, 117, 160, 2, 225, 162, 243, 173, 255, 255, 255, 255, 255, 255, 1])
assertDecodeFails([161, 2])
assertDecodeFails([161, 2, 0])
assertDecodeFails([163, 2])
assertDecodeFails([163, 2, 0])
assertDecodeFails([164, 2])
assertDecodeFails([164, 2, 0])
assertDecodeFails([165, 2])
assertDecodeFails([165, 2, 0])
assertDecodeFails([166, 2])
assertDecodeFails([166, 2, 0])
assertDecodeFails([167, 2])
assertDecodeFails([167, 2, 0])
}
func testEncoding_repeatedFixed32() {
assertEncode([170, 2, 8, 255, 255, 255, 255, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.repeatedFixed32 = [UInt32.max, UInt32.min]}
assertDecodeSucceeds([173, 2, 255, 255, 255, 127, 173, 2, 127, 127, 127, 127]) {$0.repeatedFixed32 == [2147483647, 2139062143]}
assertDecodeSucceeds([170, 2, 4, 1, 0, 0, 0, 173, 2, 255, 255, 255, 127]) {$0.repeatedFixed32 == [1, 2147483647]}
assertDecodeFails([173])
assertDecodeFails([173, 2])
assertDecodeFails([173, 2, 255])
assertDecodeFails([173, 2, 255, 255])
assertDecodeFails([173, 2, 255, 255, 255])
assertDecodeFails([173, 2, 255, 255, 255, 127, 221])
assertDecodeFails([173, 2, 255, 255, 255, 127, 173, 2])
assertDecodeFails([173, 2, 255, 255, 255, 127, 173, 2, 255])
assertDecodeFails([173, 2, 255, 255, 255, 127, 173, 2, 255, 255])
assertDecodeFails([173, 2, 255, 255, 255, 127, 173, 2, 255, 255, 255])
assertDecodeFails([168, 2])
assertDecodesAsUnknownFields([168, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([168, 2, 0, 0, 0, 0])
assertDecodeFails([169, 2])
assertDecodeFails([169, 2, 0])
assertDecodeFails([169, 2, 0, 0, 0, 0])
assertDecodeFails([171, 2])
assertDecodeFails([171, 2, 0])
assertDecodeFails([171, 2, 0, 0, 0, 0])
assertDecodeFails([172, 2])
assertDecodeFails([172, 2, 0])
assertDecodeFails([172, 2, 0, 0, 0, 0])
assertDecodeFails([174, 2])
assertDecodeFails([174, 2, 0])
assertDecodeFails([174, 2, 0, 0, 0, 0])
assertDecodeFails([175, 2])
assertDecodeFails([175, 2, 0])
assertDecodeFails([175, 2, 0, 0, 0, 0])
}
func testEncoding_repeatedFixed64() {
assertEncode([178, 2, 16, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.repeatedFixed64 = [UInt64.max, UInt64.min]}
assertDecodeSucceeds([177, 2, 255, 255, 255, 127, 0, 0, 0, 0, 177, 2, 255, 255, 255, 255, 0, 0, 0, 0, 177, 2, 255, 255, 255, 255, 255, 255, 255, 255]) {$0.repeatedFixed64 == [2147483647, 4294967295, 18446744073709551615]}
assertDecodeSucceeds([178, 2, 8, 1, 0, 0, 0, 0, 0, 0, 0]) {$0.repeatedFixed64 == [1]}
assertDecodeSucceeds([177, 2, 2, 0, 0, 0, 0, 0, 0, 0, 178, 2, 8, 1, 0, 0, 0, 0, 0, 0, 0]) {$0.repeatedFixed64 == [2, 1]}
assertDecodeFails([177])
assertDecodeFails([177, 2])
assertDecodeFails([177, 2, 255])
assertDecodeFails([177, 2, 255, 255])
assertDecodeFails([177, 2, 255, 255, 255])
assertDecodeFails([177, 2, 255, 255, 255, 127])
assertDecodeFails([177, 2, 255, 255, 255, 127, 0, 0, 0])
assertDecodeFails([176, 2])
assertDecodesAsUnknownFields([176, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([176, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([179, 2])
assertDecodeFails([179, 2, 0])
assertDecodeFails([179, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([180, 2])
assertDecodeFails([180, 2, 0])
assertDecodeFails([180, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([181, 2])
assertDecodeFails([181, 2, 0])
assertDecodeFails([181, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([182, 2])
assertDecodeFails([182, 2, 0])
assertDecodeFails([182, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([183, 2])
assertDecodeFails([183, 2, 0])
assertDecodeFails([183, 2, 0, 0, 0, 0, 0, 0, 0, 0])
}
func testEncoding_repeatedSfixed32() {
assertEncode([186, 2, 8, 255, 255, 255, 127, 0, 0, 0, 128]) {(o: inout MessageTestType) in o.repeatedSfixed32 = [Int32.max, Int32.min]}
assertDecodeSucceeds([189, 2, 0, 0, 0, 0]) {$0.repeatedSfixed32 == [0]}
assertDecodeSucceeds([186, 2, 4, 1, 0, 0, 0, 189, 2, 3, 0, 0, 0]) {$0.repeatedSfixed32 == [1, 3]}
assertDecodeFails([189])
assertDecodeFails([189, 2])
assertDecodeFails([189, 2, 0])
assertDecodeFails([189, 2, 0, 0])
assertDecodeFails([189, 2, 0, 0, 0])
assertDecodeFails([184, 2])
assertDecodesAsUnknownFields([184, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([184, 2, 0, 0, 0, 0])
assertDecodeFails([185, 2])
assertDecodeFails([185, 2, 0])
assertDecodeFails([185, 2, 0, 0, 0, 0])
assertDecodeFails([187, 2])
assertDecodeFails([187, 2, 0])
assertDecodeFails([187, 2, 0, 0, 0, 0])
assertDecodeFails([188, 2])
assertDecodeFails([188, 2, 0])
assertDecodeFails([188, 2, 0, 0, 0, 0])
assertDecodeFails([190, 2])
assertDecodeFails([190, 2, 0])
assertDecodeFails([190, 2, 0, 0, 0, 0])
assertDecodeFails([191, 2])
assertDecodeFails([191, 2, 0])
assertDecodeFails([191, 2, 0, 0, 0, 0])
}
func testEncoding_repeatedSfixed64() {
assertEncode([194, 2, 16, 255, 255, 255, 255, 255, 255, 255, 127, 0, 0, 0, 0, 0, 0, 0, 128]) {(o: inout MessageTestType) in o.repeatedSfixed64 = [Int64.max, Int64.min]}
assertDecodeSucceeds([193, 2, 0, 0, 0, 0, 0, 0, 0, 128, 193, 2, 255, 255, 255, 255, 255, 255, 255, 255, 193, 2, 1, 0, 0, 0, 0, 0, 0, 0, 193, 2, 255, 255, 255, 255, 255, 255, 255, 127]) {$0.repeatedSfixed64 == [-9223372036854775808, -1, 1, 9223372036854775807]}
assertDecodeSucceeds([194, 2, 8, 0, 0, 0, 0, 0, 0, 0, 0, 193, 2, 1, 0, 0, 0, 0, 0, 0, 0]) {$0.repeatedSfixed64 == [0, 1]}
assertDecodeFails([193])
assertDecodeFails([193, 2])
assertDecodeFails([193, 2, 0])
assertDecodeFails([193, 2, 0, 0])
assertDecodeFails([193, 2, 0, 0, 0])
assertDecodeFails([193, 2, 0, 0, 0, 0])
assertDecodeFails([193, 2, 0, 0, 0, 0, 0])
assertDecodeFails([193, 2, 0, 0, 0, 0, 0, 0])
assertDecodeFails([193, 2, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([192, 2])
assertDecodesAsUnknownFields([192, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([192, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([195, 2])
assertDecodeFails([195, 2, 0])
assertDecodeFails([195, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([196, 2])
assertDecodeFails([196, 2, 0])
assertDecodeFails([196, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([197, 2])
assertDecodeFails([197, 2, 0])
assertDecodeFails([197, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([198, 2])
assertDecodeFails([198, 2, 0])
assertDecodeFails([198, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([199, 2])
assertDecodeFails([199, 2, 0])
assertDecodeFails([199, 2, 0, 0, 0, 0, 0, 0, 0, 0])
}
func testEncoding_repeatedFloat() {
assertEncode([202, 2, 8, 0, 0, 0, 63, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.repeatedFloat = [0.5, 0.0]}
assertDecodeSucceeds([205, 2, 0, 0, 0, 63, 205, 2, 0, 0, 0, 63]) {$0.repeatedFloat == [0.5, 0.5]}
assertDecodeSucceeds([202, 2, 8, 0, 0, 0, 63, 0, 0, 0, 63]) {$0.repeatedFloat == [0.5, 0.5]}
assertDecodeFails([205, 2, 0, 0, 0, 63, 205, 2, 0, 0, 128])
assertDecodeFails([205, 2, 0, 0, 0, 63, 205, 2])
assertDecodeFails([200, 2]) // Bad byte sequence
assertDecodeFails([200, 2, 0, 0, 0, 0]) // Bad byte sequence
assertDecodeFails([201, 2]) // Bad byte sequence
assertDecodeFails([201, 2, 0, 0, 0, 0]) // Bad byte sequence
assertDecodeFails([203, 2]) // Bad byte sequence
assertDecodeFails([203, 2, 0, 0, 0, 0]) // Bad byte sequence
assertDecodeFails([204, 2]) // Bad byte sequence
assertDecodeFails([204, 2, 0, 0, 0, 0]) // Bad byte sequence
assertDecodeFails([206, 2]) // Bad byte sequence
assertDecodeFails([206, 2, 0, 0, 0, 0]) // Bad byte sequence
assertDecodeFails([207, 2]) // Bad byte sequence
assertDecodeFails([207, 2, 0, 0, 0, 0]) // Bad byte sequence
}
func testEncoding_repeatedDouble() {
assertEncode([210, 2, 16, 0, 0, 0, 0, 0, 0, 224, 63, 0, 0, 0, 0, 0, 0, 0, 0]) {(o: inout MessageTestType) in o.repeatedDouble = [0.5, 0.0]}
assertDecodeSucceeds([209, 2, 0, 0, 0, 0, 0, 0, 224, 63, 209, 2, 0, 0, 0, 0, 0, 0, 208, 63]) {$0.repeatedDouble == [0.5, 0.25]}
assertDecodeSucceeds([210, 2, 16, 0, 0, 0, 0, 0, 0, 224, 63, 0, 0, 0, 0, 0, 0, 208, 63]) {$0.repeatedDouble == [0.5, 0.25]}
assertDecodeFails([209, 2])
assertDecodeFails([209, 2, 0])
assertDecodeFails([209, 2, 0, 0])
assertDecodeFails([209, 2, 0, 0, 0, 0])
assertDecodeFails([209, 2, 0, 0, 0, 0, 0, 0, 224, 63, 209, 2])
assertDecodeFails([208, 2])
assertDecodesAsUnknownFields([208, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([208, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([211, 2])
assertDecodeFails([211, 2, 0])
assertDecodeFails([211, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([212, 2])
assertDecodeFails([212, 2, 0])
assertDecodeFails([212, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([213, 2])
assertDecodeFails([213, 2, 0])
assertDecodeFails([213, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([214, 2])
assertDecodeFails([214, 2, 0])
assertDecodeFails([214, 2, 0, 0, 0, 0, 0, 0, 0, 0])
assertDecodeFails([215, 2])
assertDecodeFails([215, 2, 0])
assertDecodeFails([215, 2, 0, 0, 0, 0, 0, 0, 0, 0])
}
func testEncoding_repeatedBool() {
assertEncode([218, 2, 3, 1, 0, 1]) {(o: inout MessageTestType) in o.repeatedBool = [true, false, true]}
assertDecodeSucceeds([216, 2, 1, 216, 2, 0, 216, 2, 0, 216, 2, 1]) {$0.repeatedBool == [true, false, false, true]}
assertDecodeSucceeds([218, 2, 3, 1, 0, 1, 216, 2, 0]) {$0.repeatedBool == [true, false, true, false]}
assertDecodeFails([216])
assertDecodeFails([216, 2])
assertDecodeFails([216, 2, 255])
assertDecodeFails([216, 2, 1, 216, 2, 255])
assertDecodeFails([217, 2])
assertDecodeFails([217, 2, 0])
assertDecodeFails([219, 2])
assertDecodeFails([219, 2, 0])
assertDecodeFails([220, 2])
assertDecodeFails([220, 2, 0])
assertDecodeFails([221, 2])
assertDecodeFails([221, 2, 0])
assertDecodeFails([222, 2])
assertDecodeFails([222, 2, 0])
assertDecodeFails([223, 2])
assertDecodeFails([223, 2, 0])
}
func testEncoding_repeatedString() {
assertEncode([226, 2, 1, 65, 226, 2, 1, 66]) {(o: inout MessageTestType) in o.repeatedString = ["A", "B"]}
assertDecodeSucceeds([226, 2, 5, 72, 101, 108, 108, 111, 226, 2, 5, 119, 111, 114, 108, 100, 226, 2, 0]) {$0.repeatedString == ["Hello", "world", ""]}
assertDecodeFails([226])
assertDecodeFails([226, 2])
assertDecodeFails([226, 2, 1])
assertDecodeFails([226, 2, 2, 65])
assertDecodeFails([226, 2, 1, 193]) // Invalid UTF-8
assertDecodeFails([224, 2])
assertDecodesAsUnknownFields([224, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([225, 2])
assertDecodeFails([225, 2, 0])
assertDecodeFails([227, 2])
assertDecodeFails([227, 2, 0])
assertDecodeFails([228, 2])
assertDecodeFails([228, 2, 0])
assertDecodeFails([229, 2])
assertDecodeFails([229, 2, 0])
assertDecodeFails([230, 2])
assertDecodeFails([230, 2, 0])
assertDecodeFails([231, 2])
assertDecodeFails([231, 2, 0])
}
func testEncoding_repeatedBytes() {
assertEncode([234, 2, 1, 1, 234, 2, 0, 234, 2, 1, 2]) {(o: inout MessageTestType) in o.repeatedBytes = [Data([1]), Data(), Data([2])]}
assertDecodeSucceeds([234, 2, 4, 0, 1, 2, 255, 234, 2, 0]) {
let ref: [[UInt8]] = [[0, 1, 2, 255], []]
for (a,b) in zip($0.repeatedBytes, ref) {
if a != Data(b) { return false }
}
return true
}
assertDecodeFails([234, 2])
assertDecodeFails([234, 2, 1])
assertDecodeFails([232, 2])
assertDecodesAsUnknownFields([232, 2, 0]) // Wrong wire type (varint), valid as an unknown field
assertDecodeFails([233, 2])
assertDecodeFails([233, 2, 0])
assertDecodeFails([235, 2])
assertDecodeFails([235, 2, 0])
assertDecodeFails([236, 2])
assertDecodeFails([236, 2, 0])
assertDecodeFails([237, 2])
assertDecodeFails([237, 2, 0])
assertDecodeFails([238, 2])
assertDecodeFails([238, 2, 0])
assertDecodeFails([239, 2])
assertDecodeFails([239, 2, 0])
}
func testEncoding_repeatedNestedMessage() {
assertEncode([130, 3, 2, 8, 1, 130, 3, 2, 8, 2]) {(o: inout MessageTestType) in
var m1 = MessageTestType.NestedMessage()
m1.bb = 1
var m2 = MessageTestType.NestedMessage()
m2.bb = 2
o.repeatedNestedMessage = [m1, m2]
}
assertDecodeFails([128, 3])
assertDecodesAsUnknownFields([128, 3, 0]) // Wrong wire type (varint), valid as an unknown field
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\nrepeated_nested_message {\n bb: 1\n}\nrepeated_nested_message {\n bb: 2\n}\n") {(o: inout MessageTestType) in
var m1 = MessageTestType.NestedMessage()
m1.bb = 1
var m2 = MessageTestType.NestedMessage()
m2.bb = 2
o.repeatedNestedMessage = [m1, m2]
}
}
func testEncoding_repeatedNestedEnum() {
assertEncode([154, 3, 2, 2, 3]) {(o: inout MessageTestType) in
o.repeatedNestedEnum = [.bar, .baz]
}
assertDebugDescription("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\nrepeated_nested_enum: [BAR, BAZ]\n") {(o: inout MessageTestType) in
o.repeatedNestedEnum = [.bar, .baz]
}
}
func testEncoding_oneofUint32() {
assertEncode([248, 6, 0]) {(o: inout MessageTestType) in o.oneofUint32 = 0}
assertDecodeSucceeds([248, 6, 255, 255, 255, 255, 15]) {$0.oneofUint32 == UInt32.max}
assertDecodeSucceeds([138, 7, 1, 97, 248, 6, 1]) {(o: MessageTestType) in
if case .oneofUint32? = o.oneofField, o.oneofUint32 == UInt32(1) {
return true
}
return false
}
assertDecodeFails([248, 6, 128]) // Bad varint
// Bad wire types:
assertDecodeFails([249, 6])
assertDecodeFails([249, 6, 0])
assertDecodeFails([250, 6])
assertDecodesAsUnknownFields([250, 6, 0]) { // Wrong wire type (length delimited), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodeFails([251, 6])
assertDecodeFails([251, 6, 0])
assertDecodeFails([252, 6])
assertDecodeFails([252, 6, 0])
assertDecodeFails([253, 6])
assertDecodeFails([253, 6, 0])
assertDecodeFails([254, 6])
assertDecodeFails([254, 6, 0])
assertDecodeFails([255, 6])
assertDecodeFails([255, 6, 0])
var m = MessageTestType()
m.oneofUint32 = 77
XCTAssertEqual(m.debugDescription, "SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noneof_uint32: 77\n")
var m2 = MessageTestType()
m2.oneofUint32 = 78
XCTAssertNotEqual(m.hashValue, m2.hashValue)
}
func testEncoding_oneofNestedMessage() {
assertEncode([130, 7, 2, 8, 1]) {(o: inout MessageTestType) in
o.oneofNestedMessage = MessageTestType.NestedMessage()
o.oneofNestedMessage.bb = 1
}
assertDecodeSucceeds([130, 7, 0]) {(o: MessageTestType) in
if case .oneofNestedMessage(let m)? = o.oneofField {
return m.bb == 0
}
return false
}
assertDecodeSucceeds([248, 6, 0, 130, 7, 2, 8, 1]) {(o: MessageTestType) in
if case .oneofUint32? = o.oneofField {
return false
}
if case .oneofNestedMessage(let m)? = o.oneofField {
return m.bb == 1
}
return false
}
}
func testEncoding_oneofNestedMessage1() {
assertDecodeSucceeds([130, 7, 2, 8, 1, 248, 6, 0]) {(o: MessageTestType) in
if case .oneofUint32? = o.oneofField, o.oneofUint32 == UInt32(0) {
return true
}
return false
}
// Unkonwn field within nested message should not break decoding
assertDecodeSucceeds([130, 7, 5, 128, 127, 0, 8, 1, 248, 6, 0]) {(o: MessageTestType) in
if case .oneofUint32? = o.oneofField, o.oneofUint32 == 0 {
return true
}
return false
}
}
func testEncoding_oneofNestedMessage2() {
var m = MessageTestType()
m.oneofNestedMessage = MessageTestType.NestedMessage()
m.oneofNestedMessage.bb = 1
XCTAssertEqual(m.debugDescription, "SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noneof_nested_message {\n bb: 1\n}\n")
var m2 = MessageTestType()
m2.oneofNestedMessage = MessageTestType.NestedMessage()
m2.oneofNestedMessage.bb = 2
XCTAssertNotEqual(m.hashValue, m2.hashValue)
}
func testEncoding_oneofNestedMessage9() {
assertDecodeFails([128, 7])
assertDecodesAsUnknownFields([128, 7, 0]) { // Wrong wire type (varint), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodeFails([129, 7])
assertDecodeFails([129, 7, 0])
assertDecodeFails([131, 7])
assertDecodeFails([131, 7, 0])
assertDecodeFails([132, 7])
assertDecodeFails([132, 7, 0])
assertDecodeFails([133, 7])
assertDecodeFails([133, 7, 0])
assertDecodeFails([134, 7])
assertDecodeFails([134, 7, 0])
assertDecodeFails([135, 7])
assertDecodeFails([135, 7, 0])
}
func testEncoding_oneofString() {
assertEncode([138, 7, 1, 97]) {(o: inout MessageTestType) in o.oneofString = "a"}
assertDecodeSucceeds([138, 7, 1, 97]) {$0.oneofString == "a"}
assertDecodeSucceeds([138, 7, 0]) {$0.oneofString == ""}
assertDecodeSucceeds([146, 7, 0, 138, 7, 1, 97]) {(o:MessageTestType) in
if case .oneofString? = o.oneofField, o.oneofString == "a" {
return true
}
return false
}
assertDecodeFails([138, 7, 1]) // Truncated body
assertDecodeFails([138, 7, 1, 192]) // Malformed UTF-8
// Bad wire types:
assertDecodesAsUnknownFields([136, 7, 0]) { // Wrong wire type (varint), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodesAsUnknownFields([136, 7, 1]) { // Wrong wire type (varint), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodesAsUnknownFields([137, 7, 1, 1, 1, 1, 1, 1, 1, 1]) { // Wrong wire type (fixed64), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodeFails([139, 7]) // Wire type 3
assertDecodeFails([140, 7]) // Wire type 4
assertDecodeFails([141, 7, 0]) // Wire type 5
assertDecodesAsUnknownFields([141, 7, 0, 0, 0, 0]) { // Wrong wire type (fixed32), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodeFails([142, 7]) // Wire type 6
assertDecodeFails([142, 7, 0]) // Wire type 6
assertDecodeFails([143, 7]) // Wire type 7
assertDecodeFails([143, 7, 0]) // Wire type 7
var m = MessageTestType()
m.oneofString = "abc"
XCTAssertEqual(m.debugDescription, "SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noneof_string: \"abc\"\n")
var m2 = MessageTestType()
m2.oneofString = "def"
XCTAssertNotEqual(m.hashValue, m2.hashValue)
}
func testEncoding_oneofBytes() {
assertEncode([146, 7, 1, 1]) {(o: inout MessageTestType) in o.oneofBytes = Data([1])}
}
func testEncoding_oneofBytes2() {
assertDecodeSucceeds([146, 7, 1, 1]) {(o: MessageTestType) in
let expectedB = Data([1])
if case .oneofBytes(let b)? = o.oneofField {
let s = o.oneofString
return b == expectedB && s == ""
}
return false
}
}
func testEncoding_oneofBytes3() {
assertDecodeSucceeds([146, 7, 0]) {(o: MessageTestType) in
let expectedB = Data()
if case .oneofBytes(let b)? = o.oneofField {
let s = o.oneofString
return b == expectedB && s == ""
}
return false
}
}
func testEncoding_oneofBytes4() {
assertDecodeSucceeds([138, 7, 1, 97, 146, 7, 0]) {(o: MessageTestType) in
let expectedB = Data()
if case .oneofBytes(let b)? = o.oneofField {
let s = o.oneofString
return b == expectedB && s == ""
}
return false
}
}
func testEncoding_oneofBytes5() {
// Setting string and then bytes ends up with bytes but no string
assertDecodeFails([146, 7])
}
func testEncoding_oneofBytes_failures() {
assertDecodeFails([146, 7, 1])
// Bad wire types:
assertDecodeFails([144, 7])
assertDecodesAsUnknownFields([144, 7, 0]) { // Wrong wire type (varint), valid as an unknown field
$0.oneofField == nil // oneof doesn't get set.
}
assertDecodeFails([145, 7])
assertDecodeFails([145, 7, 0])
assertDecodeFails([147, 7])
assertDecodeFails([147, 7, 0])
assertDecodeFails([148, 7])
assertDecodeFails([148, 7, 0])
assertDecodeFails([149, 7])
assertDecodeFails([149, 7, 0])
assertDecodeFails([150, 7])
assertDecodeFails([150, 7, 0])
assertDecodeFails([151, 7])
assertDecodeFails([151, 7, 0])
}
func testEncoding_oneofBytes_debugDescription() {
var m = MessageTestType()
m.oneofBytes = Data([1, 2, 3])
XCTAssertEqual(m.debugDescription, "SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noneof_bytes: \"\\001\\002\\003\"\n")
var m2 = MessageTestType()
m2.oneofBytes = Data([4, 5, 6])
XCTAssertNotEqual(m.hashValue, m2.hashValue)
}
func testDebugDescription() {
var m = MessageTestType()
let d = m.debugDescription
XCTAssertEqual("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\n", d)
m.optionalInt32 = 7
XCTAssertEqual("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_int32: 7\n", m.debugDescription)
m.repeatedString = ["a", "b"]
XCTAssertEqual("SwiftProtobufTests.Proto3Unittest_TestAllTypes:\noptional_int32: 7\nrepeated_string: \"a\"\nrepeated_string: \"b\"\n", m.debugDescription)
}
func testDebugDescription2() {
// Message with only one field
var m = ProtobufUnittest_ForeignMessage()
XCTAssertEqual("SwiftProtobufTests.ProtobufUnittest_ForeignMessage:\n", m.debugDescription)
m.c = 3
XCTAssertEqual("SwiftProtobufTests.ProtobufUnittest_ForeignMessage:\nc: 3\n", m.debugDescription)
}
func testDebugDescription3() {
// Message with only a optional oneof
var m = ProtobufUnittest_TestOneof()
XCTAssertEqual("SwiftProtobufTests.ProtobufUnittest_TestOneof:\n", m.debugDescription)
m.fooInt = 1
XCTAssertEqual("SwiftProtobufTests.ProtobufUnittest_TestOneof:\nfoo_int: 1\n", m.debugDescription)
m.fooString = "a"
XCTAssertEqual("SwiftProtobufTests.ProtobufUnittest_TestOneof:\nfoo_string: \"a\"\n", m.debugDescription)
var g = ProtobufUnittest_TestOneof.FooGroup()
g.a = 7
g.b = "b"
m.fooGroup = g
XCTAssertEqual("SwiftProtobufTests.ProtobufUnittest_TestOneof:\nFooGroup {\n a: 7\n b: \"b\"\n}\n", m.debugDescription)
}
}
|
047afb500bd858d851db0272a0816139
| 45.281573 | 268 | 0.599043 | false | true | false | false |
Shopify/mobile-buy-sdk-ios
|
refs/heads/main
|
Buy/Generated/Storefront/CheckoutLineItemEdge.swift
|
mit
|
1
|
//
// CheckoutLineItemEdge.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
extension Storefront {
/// An auto-generated type which holds one CheckoutLineItem and a cursor during
/// pagination.
open class CheckoutLineItemEdgeQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CheckoutLineItemEdge
/// A cursor for use in pagination.
@discardableResult
open func cursor(alias: String? = nil) -> CheckoutLineItemEdgeQuery {
addField(field: "cursor", aliasSuffix: alias)
return self
}
/// The item at the end of CheckoutLineItemEdge.
@discardableResult
open func node(alias: String? = nil, _ subfields: (CheckoutLineItemQuery) -> Void) -> CheckoutLineItemEdgeQuery {
let subquery = CheckoutLineItemQuery()
subfields(subquery)
addField(field: "node", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// An auto-generated type which holds one CheckoutLineItem and a cursor during
/// pagination.
open class CheckoutLineItemEdge: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CheckoutLineItemEdgeQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "cursor":
guard let value = value as? String else {
throw SchemaViolationError(type: CheckoutLineItemEdge.self, field: fieldName, value: fieldValue)
}
return value
case "node":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CheckoutLineItemEdge.self, field: fieldName, value: fieldValue)
}
return try CheckoutLineItem(fields: value)
default:
throw SchemaViolationError(type: CheckoutLineItemEdge.self, field: fieldName, value: fieldValue)
}
}
/// A cursor for use in pagination.
open var cursor: String {
return internalGetCursor()
}
func internalGetCursor(alias: String? = nil) -> String {
return field(field: "cursor", aliasSuffix: alias) as! String
}
/// The item at the end of CheckoutLineItemEdge.
open var node: Storefront.CheckoutLineItem {
return internalGetNode()
}
func internalGetNode(alias: String? = nil) -> Storefront.CheckoutLineItem {
return field(field: "node", aliasSuffix: alias) as! Storefront.CheckoutLineItem
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "node":
response.append(internalGetNode())
response.append(contentsOf: internalGetNode().childResponseObjectMap())
default:
break
}
}
return response
}
}
}
|
e7b664f585c40796d76080cd790175b3
| 33.702703 | 115 | 0.728193 | false | false | false | false |
blueXstar597/GA-AI-Simluation-in-Swift
|
refs/heads/master
|
Sprint 3 Final/GG 2/GG/GameScene.swift
|
apache-2.0
|
1
|
//
// GameScene.swift
// 2DSimatulorAI
//
// Created by Student on 2017-06-03.
// Copyright © 2017 Danny. All rights reserved.
//
import SpriteKit
import GameplayKit
//Setting a previous update time to compare the delta
var lastUpdateTime: TimeInterval = 0
let MaxHealth: CGFloat = 100
let HealthBarWidth: CGFloat = 40
let HealthBarHeight: CGFloat = 4
let Population = 20
var Generation = 1
var Fitness: CGFloat = 0
var PopulationDNA = [[Int]] ()
var largest : CGFloat = 0
var GreatestDNA = [Int] ()
//Genetics Evolution
var GroupFitness: [CGFloat] = Array (repeating: 0, count: Population)
var SplitNeuralWeights = [[CGFloat]] ()
var NeuralWeights = [[CGFloat]] ()
struct game {
static var IsOver : Bool = false
}
enum ColliderType: UInt32 {
case player = 1
case obstacles = 2
case food = 4
case wall = 8
case Sensor = 16
}
//#MARK : MATH GROUP
//Enable Vector Properties
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
#if !(arch(x86_64) || arch(arm64))
func sqrt(a: CGFloat) -> CGFloat {
return CGFloat(sqrtf(Float(a)))
}
#endif
//Develop to 2D vectors maths and techiques
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalized() -> CGPoint {
return self / length()
}
func angleForVector () -> CGFloat{
var alfa: CGFloat = atan2 (self.y,self.x)
return alfa
}
}
//Creating a random min and max function
func random (min: Float, max: Float) -> Float
{
let random = Float (Double (arc4random()%1000) / (1000.0))
return random * (max-min) + min
}
//------------------------------
//Develop the class scene
class GameScene: SKScene, SKPhysicsContactDelegate {
//Create SKSpirtNode and Picture
//Set Parameter for the Wander Algthorim
let radius: CGFloat = 5
let distance: CGFloat = 50
let angleNosise: Float = 0.3
let speedD: CGFloat = 10 //20
var angle : [CGFloat] = Array (repeating: 0, count: Population)
var Circle = [SKSpriteNode] ()
var Target = [SKSpriteNode] ()
var counter = 0
//Save every location - (Rather than saving every point, the points are updated every 5 seconds)
var locationObstacle = [CGPoint] ()
var locationFood = [CGPoint] ()
//Fitness Score and Generation #
var scoreLabel: SKLabelNode!
var genLabel : SKLabelNode!
var largestLabel : SKLabelNode!
var bestLabel: SKLabelNode!
var possibleChar = ["player1","player2","player3"]
var possibleObs = ["obstacles0", "obstacles1"]
//Generate a gameTimer to recrod and update everytime
var ObsTimer: Timer!
var FoodTimer: Timer!
//Player's Properties and Behavior
var HealthBar = [SKSpriteNode] ()
var playerHP : [CGFloat] = Array (repeating: MaxHealth, count: Population)
var foodeaten = Array (repeating: 0, count: Population)
//Setuping AI System and Connect to Neural Network
var AIradius: CGFloat = 40
var playerRef: [CGFloat] = Array (repeating: 0, count: Population)
var locationObjPos = ([Int](), [SKSpriteNode] (), [SKSpriteNode] ())
var FieldView: CGFloat = 180
var ReponseSystem = Array (repeating: 0, count: Population)
var NewWeights = [[CGFloat]] ()
//Set-up Function and the new World
override func didMove(to view: SKView) {
//Set BackGround and Wall to white
backgroundColor = SKColor.white
self.physicsWorld.contactDelegate = self
//Develop Edge detection
var edge = SKSpriteNode()
edge.color = UIColor.black
let edgeRect = CGRect (x: 0, y:0 , width:frame.size.width, height:frame.size.height)
edge.physicsBody = SKPhysicsBody (edgeLoopFrom: edgeRect)
//Allow Wall to have collision and set-up physics
edge.physicsBody!.categoryBitMask = ColliderType.wall.rawValue
//edge.physicsBody!.collisionBitMask = ColliderType.player.rawValue
edge.physicsBody!.contactTestBitMask = ColliderType.player.rawValue
edge.physicsBody!.isDynamic = false
edge.name = "wall"
addChild(edge)
//Develop the Players
for _ in 0...Population - 1
{
self.addPlayer()
counter += 1
}
//If 1st Generation, the genes are randomly generated
if Generation == 1
{
PopulationDNA = PopulationMod()
for Individuals in 0...Population - 1
{
SplitNeuralWeights.append ((ConvertBinToNum(Binary: PopulationDNA [Individuals])))
NeuralWeights.append ((FromGreyToWeights(Binary: SplitNeuralWeights [Individuals])))
}
}
else
{
//Else the gene is carried through its parent
for Individuals in 0...Population - 1
{
NewWeights.append ((ConvertBinToNum(Binary: PopulationDNA [Individuals])))
//A Evalution Method to detect the presence of mutation
if areEqual(NewWeight: NewWeights [Individuals], OldWeight: SplitNeuralWeights [Individuals])
{
print ("No Mutation \(Individuals)")
}
else
{
print ("Yes Mutation \(Individuals)")
SplitNeuralWeights [Individuals] = NewWeights [Individuals]
}
//Save into the neural network
NeuralWeights.append ((FromGreyToWeights(Binary: SplitNeuralWeights [Individuals])))
}
}
//Set a counter
counter = 0
// Score Label //
scoreLabel = SKLabelNode(text: "Fitness: \(Int(Fitness))")
scoreLabel.position = CGPoint (x: 115, y:self.frame.size.height - 60)
scoreLabel.fontSize = 36
scoreLabel.fontColor = UIColor.black
self.addChild (scoreLabel)
//Generation Label
genLabel = SKLabelNode (text: "Generation \(Generation)")
genLabel.position = CGPoint (x: 110, y: self.frame.size.height - 100)
genLabel.fontSize = 36
genLabel.fontColor = UIColor.blue
self.addChild (genLabel)
//Greatest Label
largestLabel = SKLabelNode (text: "Greatest: \(Int(largest))")
largestLabel.position = CGPoint (x: 110, y: self.frame.size.height - 140)
largestLabel.fontSize = 36
largestLabel.fontColor = UIColor.black
self.addChild (largestLabel)
//Update every second for the addObstacle
ObsTimer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(addObstacle), userInfo: nil, repeats: true)
//AddFood
FoodTimer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(addFood), userInfo: nil, repeats: true)
}
//Method to develop player
func addPlayer()
{
//Set a SpriteImage
let ri = Int(arc4random_uniform(UInt32(possibleChar.count)))
//Declare Players and Physics
let player = SKSpriteNode(imageNamed: "player\(ri)")
let playerHealthBar = SKSpriteNode ()
player.position = CGPoint (x:self.frame.size.width/2 , y:self.frame.size.height/2)
self.physicsWorld.gravity = CGVector (dx: 0, dy: 0)
//Physics and Collision for Player
player.physicsBody = SKPhysicsBody (rectangleOf: player.size)
player.physicsBody?.categoryBitMask = ColliderType.player.rawValue
player.physicsBody?.collisionBitMask = ColliderType.obstacles.rawValue //|ColliderType.wall.rawValue
player.physicsBody?.contactTestBitMask = ColliderType.obstacles.rawValue | ColliderType.wall.rawValue
player.physicsBody?.usesPreciseCollisionDetection = true
player.physicsBody?.isDynamic = true
player.physicsBody?.restitution = 1.0;
player.physicsBody?.friction = 0.0;
player.physicsBody?.linearDamping = 0.0;
player.physicsBody?.angularDamping = 0.0;
player.name = "player"
player.userData = NSMutableDictionary ()
player.userData?.setValue(counter, forKey: "Key")
self.addChild(player)
//Set the health bar to the player
playerHealthBar.position = CGPoint (
x: player.position.x,
y: player.position.y - player.size.height/2 - 15
)
self.addChild(playerHealthBar)
//Save the health num
HealthBar.append (playerHealthBar)
//Develop and Setup the Wander Algthroim - Detector/ Position
let circle = SKSpriteNode (imageNamed: "circle")
circle.position = CGPoint (x: 0 + player.position.x,y: distance + player.position.y)
circle.xScale = radius/50
circle.yScale = radius/50
circle.physicsBody = SKPhysicsBody (circleOfRadius: circle.size.width + 15)
circle.physicsBody!.categoryBitMask = ColliderType.Sensor.rawValue
circle.physicsBody?.collisionBitMask = 0
//Need for a FOV detection
circle.physicsBody?.contactTestBitMask = ColliderType.food.rawValue | ColliderType.obstacles.rawValue | ColliderType.player.rawValue
circle.userData = NSMutableDictionary ()
circle.userData?.setValue(counter, forKey: "Key")
self.addChild(circle)
Circle.append(circle)
//Wander Algortim - Sliding Transition
let target = SKSpriteNode (imageNamed: "")
target.position = CGPoint (x:0 + circle.position.x, y: radius + circle.position.y )
target.xScale = radius / 2000
target.yScale = radius / 2000
self.addChild(target)
Target.append(target)
}
//Adding Obstacle and entitles
func addObstacle()
{
let ri = Int(arc4random_uniform(UInt32(possibleObs.count)))
//Declare Obsctacles for Local Variables
let localobstacle = SKSpriteNode (imageNamed: "obstacles\(ri)")
//Contain a physics body on the local variables
localobstacle.physicsBody = SKPhysicsBody (rectangleOf: localobstacle.size)
//Allow Collision to take place with certain Item ID
localobstacle.physicsBody?.categoryBitMask = ColliderType.obstacles.rawValue
localobstacle.physicsBody?.contactTestBitMask = ColliderType.player.rawValue
localobstacle.physicsBody?.collisionBitMask = ColliderType.player.rawValue
localobstacle.physicsBody?.isDynamic = false
localobstacle.physicsBody?.usesPreciseCollisionDetection = true
//Name the local obstacles
localobstacle.name = "obstacle"
//Selecting a random x and y position
while (true)
{
//Use a bool to exit the random poistion searching
var gate = true
let randomX : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.width - 100))+55)
let randomY : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.height - 150))+50)
//Set poisition based on random Point
localobstacle.position = CGPoint(x: randomX,y: randomY)
//If there is no obstacles within the area
if locationObstacle.count == 0
{
//Add obstacles into the ground
locationObstacle.append (localobstacle.position)
self.addChild(localobstacle)
break
}
//However, if != 0
for sprite in 0 ... locationObstacle.count - 1
{
//Set a range of position that is not inbetween the obstacle's range (The obstacle will range about 20 units long from each other)
if (localobstacle.position.x > locationObstacle [sprite].x - 30 && localobstacle.position.x < locationObstacle [sprite].x + 30 ) && (localobstacle.position.y > locationObstacle [sprite].y - 30 &&
localobstacle.position.y < locationObstacle [sprite].y + 30)
{
//But, if it lies witin another obstacle range
//Re-determine the random function
gate = false
break
}
}
//If the random Point is safe
if gate == true
{
//Store and break out of the random loop
locationObstacle.append (localobstacle.position)
self.addChild(localobstacle)
break
}
}
}
//Develop Food and Image
func addFood ()
{
//Set up SpriteNode and Image
let localFood = SKSpriteNode (imageNamed: "food")
localFood.physicsBody = SKPhysicsBody (rectangleOf: localFood.size)
localFood.physicsBody?.categoryBitMask = ColliderType.food.rawValue
localFood.physicsBody?.contactTestBitMask = ColliderType.player.rawValue
localFood.physicsBody?.collisionBitMask = ColliderType.player.rawValue
localFood.physicsBody?.isDynamic = false
localFood.physicsBody?.usesPreciseCollisionDetection = true
localFood.name = "food"
while true
{
//Find Random Position and see if it is safe, if it is, allow to place
var gate = true
let randomX : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.width - 100))+55)
let randomY : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.height - 150))+50)
//Set poisition based on random Point
localFood.position = CGPoint(x: randomX,y: randomY)
//If there is no obstacles within the area
if locationFood.count == 0
{
//Add obstacles into the ground
locationFood.append (localFood.position)
self.addChild(localFood)
break
}
//However, if != 0
for sprite in 0 ... locationFood.count - 1
{
//Set a range of position that is not inbetween the obstacle's range (The obstacle will range about 20 units long from each other)
if (localFood.position.x > locationFood [sprite].x - 30 && localFood.position.x < locationFood [sprite].x + 30 ) && (localFood.position.y > locationFood [sprite].y - 30 &&
localFood.position.y < locationFood [sprite].y + 30)
{
//But, if it lies witin another obstacle range
//Re-determine the random function
gate = false
break
}
}
//If the random Point is safe
if gate == true
{
//Store and break out of the random loop
locationFood.append (localFood.position)
self.addChild(localFood)
break
}
}
}
//Function for updating the player's speed and direction
func updatePlayer (player: SKSpriteNode,health: SKSpriteNode, target: SKSpriteNode, circle: SKSpriteNode, counter: Int )
{
//Design a desireable location
var targetLoc = target.position
//Find the distance in between the target and the player
var desiredDirection = CGPoint (x: targetLoc.x - player.position.x ,y: targetLoc.y - player.position.y )
//Normalized the distance to a unit of 1
desiredDirection = desiredDirection.normalized()
//Find the speed and its movement
let velocity = CGPoint (x: desiredDirection.x*speedD, y:desiredDirection.y*speedD)
//Re-position the player
player.position = CGPoint (x: player.position.x + velocity.x, y: player.position.y + velocity.y)
player.zRotation = velocity.angleForVector() - 90 * CGFloat (M_PI/180)
playerRef.append (player.zRotation)
//See if the player exit out of the screen, reposition themselves
if (player.position.x >= frame.size.width)
{
player.position = CGPoint (x:player.position.x - size.width,y:player.position.y)
}
if (player.position.x <= 0)
{
player.position = CGPoint (x:player.position.x + size.width,y:player.position.y)
}
if (player.position.y >= frame.size.height)
{
player.position = CGPoint (x:player.position.x,y:player.position.y - size.height)
}
if (player.position.y <= 0)
{
player.position = CGPoint (x:player.position.x,y:player.position.y + size.height)
}
//Reposition the Health bar to match up the player
health.position = CGPoint (
x: player.position.x,
y: player.position.y - player.size.height/2 - 15
)
//Decrease its health according to movement
playerHP [counter] -= 1
//Declare a circle location, which takes in the unit 1
var circleLoc = velocity.normalized()
//Re-define the circleLoc to maintain its distance and take in the travelled distance
circleLoc = CGPoint (x: circleLoc.x*distance, y: circleLoc.y*distance)
//Reset the position of the circle's location to continue the player's circular movement
circleLoc = CGPoint (x: player.position.x + circleLoc.x, y: player.position.y + circleLoc.y)
//Develop an angle for the player to move within
if ReponseSystem [counter] == 2
{
angle [counter] = angle [counter] + CGFloat (-angleNosise) //Left
//print ("left")
}
else if ReponseSystem [counter] == 1
{
angle [counter] = angle [counter] + CGFloat (angleNosise) //Right
//print ("right")
}
else
{
angle [counter] = angle [counter] + CGFloat (random(min: -angleNosise, max: angleNosise))
}
//Empty out the response system after response
ReponseSystem [counter] = 0
//Use direction vectors to calculate the x and y component of the point
var perimitterPoint = CGPoint (x: CGFloat (cosf(Float(angle [counter]))),y: CGFloat(sinf(Float(angle [counter]))))
//The "sliding" effect within the target poistion
perimitterPoint = CGPoint (x: perimitterPoint.x * radius, y: perimitterPoint.y * radius)
//Relocate the target loc to mimic the steering effect within the circle
targetLoc = CGPoint (x: circleLoc.x + perimitterPoint.x, y: circleLoc.y + perimitterPoint.y)
//Re-define the location of the circle and the target to allow for continous movement
circle.position = circleLoc
target.position = targetLoc
}
//Deleting Nodes
func deleteNodes (Onebody: SKSpriteNode)
{
Onebody.removeFromParent()
Onebody.physicsBody = nil
}
//Collision and Contact Dectection
func didBegin(_ contact: SKPhysicsContact)
{
var firstBody : SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask == ColliderType.player.rawValue && contact.bodyB.categoryBitMask == ColliderType.obstacles.rawValue
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else if contact.bodyB.categoryBitMask == ColliderType.player.rawValue && contact.bodyA.categoryBitMask == ColliderType.obstacles.rawValue
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else if contact.bodyA.categoryBitMask == ColliderType.player.rawValue && contact.bodyB.categoryBitMask == ColliderType.food.rawValue
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else if contact.bodyB.categoryBitMask == ColliderType.player.rawValue && contact.bodyA.categoryBitMask == ColliderType.food.rawValue
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else if contact.bodyB.categoryBitMask == ColliderType.Sensor.rawValue
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else if contact.bodyA.categoryBitMask == ColliderType.Sensor.rawValue
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else
{
return
}
//Object Collision
if let firstNode = firstBody.node as? SKSpriteNode,
let secondNode = secondBody.node as? SKSpriteNode
{
if firstBody.categoryBitMask == ColliderType.player.rawValue &&
secondBody.categoryBitMask == ColliderType.obstacles.rawValue
{
deleteNodes(Onebody: secondNode)
if let playerNode = firstBody.node
{
if let num = playerNode.userData?.value(forKey: "Key") as? Int
{
playerHP [num] -= 100
foodeaten [num] += 1
}
}
}
if firstBody.categoryBitMask == ColliderType.player.rawValue &&
secondBody.categoryBitMask == ColliderType.food.rawValue
{
deleteNodes(Onebody: secondNode)
if let playerNode = firstBody.node
{
if let num = playerNode.userData?.value(forKey:"Key") as? Int
{
playerHP [num] += 50
if playerHP [num] > 500
{
playerHP [num] = MaxHealth
}
}
}
}
if firstBody.categoryBitMask == ColliderType.Sensor.rawValue && (secondBody.categoryBitMask == ColliderType.food.rawValue || secondBody.categoryBitMask == ColliderType.obstacles.rawValue || secondBody.categoryBitMask == ColliderType.player.rawValue)
{
if let playerPos = firstBody.node
{
if let num = playerPos.userData?.value(forKey: "Key") as? Int
{
locationObjPos.0.append (num)
locationObjPos.1.append (firstBody.node as! SKSpriteNode)
locationObjPos.2.append (secondBody.node as! SKSpriteNode)
}
}
}
else if secondBody.categoryBitMask == ColliderType.Sensor.rawValue && firstBody.categoryBitMask == ColliderType.food.rawValue | ColliderType.obstacles.rawValue | ColliderType.player.rawValue
{
if let playerPos = secondBody.node
{
if let num = playerPos.userData?.value(forKey: "Key") as? Int
{
locationObjPos.0.append(num)
locationObjPos.1.append (firstBody.node as! SKSpriteNode)
locationObjPos.2.append(secondBody.node as! SKSpriteNode)
}
}
}
}
}
//Develop the FOV AI for the player
func AISensor(numValue: [Int], playPos: [SKSpriteNode], objPos: [SKSpriteNode])
{
var input = Array (repeating: CGFloat (0.0), count: 36)
var Allow = false
if numValue.count == 0
{
return
}
for individual in 0...numValue.count - 1
{
for tracking in 0...objPos.count - 1
{
var Setfactor = 1
if objPos [tracking].physicsBody?.categoryBitMask == ColliderType.food.rawValue
{
//Food Section - Neuron
Setfactor = 1
}
else if objPos [tracking].physicsBody?.categoryBitMask == ColliderType.obstacles.rawValue
{
//Obstacles Section - Neuron
Setfactor = 2
}
else if objPos [tracking].physicsBody?.categoryBitMask == ColliderType.player.rawValue
{
//Player Section - Neuron
Setfactor = 3
}
//1
let gapLength = CGPoint (x: playPos [individual].position.x - objPos [tracking].position.x, y: playPos [individual].position.y - objPos [tracking].position.y)
let gapDistance = gapLength.length()
let AngluarPos: CGFloat = atan2 (CGFloat(gapLength.y), CGFloat(gapLength.x))
if AIradius > gapDistance
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/2) && AngluarPos < (playerRef [numValue [individual]] + FieldView/2)
{
Allow = true
//Left Side of the 90 deg
if AngluarPos > (playerRef [numValue [individual]] - FieldView/2)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//1
input [Setfactor - 1] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//2
input [Setfactor + 2] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6) && AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//3
input [Setfactor + 5] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//4
input [Setfactor + 8] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//5
input [Setfactor + 11] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//6
input [Setfactor + 14] = gapDistance
}
}
}
//Right Side of the 90 deg
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/2)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//7
input [Setfactor + 17] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//8
input [Setfactor + 20] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6) && AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//9
input [Setfactor + 23] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//10
input [Setfactor + 26] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//11
input [Setfactor + 29] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//12
input [Setfactor + 32] = gapDistance
}
}
}
}
}
}
if Allow == true
{
//If accesses the FOV, it activates the neural network
ReponseSystem [numValue [individual]] = NeuralNetwork(Parent: PopulationDNA [numValue [individual]], Weights: NeuralWeights [numValue[individual]], Sensory: input)
input = Array (repeating: CGFloat (0.0), count: 36)
}
}
}
func updateHealthBar(node: SKSpriteNode, withHealthPoints hp: CGFloat) {
let barSize = CGSize(width: HealthBarWidth, height: HealthBarHeight);
let fillColor = UIColor(red: 113.0/255, green: 202.0/255, blue: 53.0/255, alpha:1)
let borderColor = UIColor(red: 35.0/255, green: 28.0/255, blue: 40.0/255, alpha:1)
// create drawing context
UIGraphicsBeginImageContextWithOptions(barSize, false, 0)
let context = UIGraphicsGetCurrentContext()
// draw the outline for the health bar
borderColor.setStroke()
let borderRect = CGRect(origin: CGPoint.zero, size: barSize)
context!.stroke(borderRect, width: 1)
// draw the health bar with a colored rectangle
fillColor.setFill()
let barWidth = (barSize.width - 1) * CGFloat(hp) / CGFloat(MaxHealth)
let barRect = CGRect(x: 0.5, y: 0.5, width: barWidth, height: barSize.height - 1)
context!.fill(barRect)
// extract image
let spriteImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// set sprite texture and size
node.texture = SKTexture(image: spriteImage!)
node.size = barSize
}
func goToGameScene ()
{
let gameScene: GameScene = GameScene(size: self.view!.bounds.size) // create your new scene
let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions)
gameScene.scaleMode = SKSceneScaleMode.fill
self.view!.presentScene(gameScene, transition: transition)
}
//Update within frames
override func update(_ currentTime: TimeInterval) {
//Update players
self.enumerateChildNodes(withName: "player")
{
node, stop in
if let num = node.userData?.value(forKey: "Key") as? Int
{
self.updatePlayer(player:node as! SKSpriteNode, health:self.HealthBar [num], target: self.Target [num], circle: self.Circle [num], counter: num)
if self.playerHP [num] <= 0
{
self.deleteNodes(Onebody: node as! SKSpriteNode)
GroupFitness [num] = EvalutionMod(Time: currentTime, Food: self.foodeaten [num])
}
self.updateHealthBar(node: self.HealthBar [num], withHealthPoints: self.playerHP [num])
self.counter += 1
}
}
if counter == 0
{
game.IsOver = true
Generation += 1
let Picker = RouletteSel(Generation: PopulationDNA ,GenFitness: GroupFitness)
var breeding = [[Int]] ()
var breedingWeights = [[CGFloat]] ()
for x in 0...Picker.count - 1
{
breeding.append (PopulationDNA [Picker [x]])
breedingWeights.append (SplitNeuralWeights [Picker [x]])
}
(PopulationDNA,SplitNeuralWeights) = CrossingOver(Population: breeding, inDividualWeight: breedingWeights)
PopulationDNA = Mutation(Population: PopulationDNA)
NeuralWeights = [[CGFloat]] ()
lastUpdateTime = currentTime
removeAllChildren()
goToGameScene()
}
counter = 0
//If the node of the obstacle exceed 6, the obstacle will relocate themselves
if locationObstacle.count >= 10
{
//In the child node, where the node are called "obstacles"
self.enumerateChildNodes(withName: "obstacle")
{
node, stop in
//Remove nodes within the parent node
node.removeFromParent();
node.physicsBody = nil
}
//Clear the location of the stored nodes (obstacles)
locationObstacle = []
}
if locationFood.count >= 10
{
self.enumerateChildNodes(withName: "food")
{
node, stop in
node.removeFromParent();
node.physicsBody = nil
}
locationFood = []
}
AISensor(numValue: locationObjPos.0, playPos: locationObjPos.1, objPos: locationObjPos.2)
playerRef = Array (repeating: 0, count: Population)
}
}
|
428081c80039af8c6048877deeebadd6
| 41.820732 | 261 | 0.549768 | false | false | false | false |
gaoleegin/SwiftLianxi
|
refs/heads/master
|
自定义NSOperation/自定义NSOperation/LJOperation.swift
|
apache-2.0
|
1
|
//
// LJOperation.swift
// 自定义NSOperation
// Created by 高李军 on 15/11/26.
// Copyright © 2015年 高李军. All rights reserved.
//
import UIKit
class LJOperation: NSOperation {
class func downImage(urlString:String,finshed:(imge:UIImage)->())->LJOperation{
let op = LJOperation()
op.urlString = urlString
op.finshed = finshed
return op
}
var urlString:String?
var finshed:((image:UIImage)->())?
override func main() {
print(NSThread.currentThread())
print("已经调用了")
assert(1 == 3, "不可以从这里") ///这就是一个断言,如果不满足条件
let imageData = NSData(contentsOfURL: NSURL(string: self.urlString!)!)
let image:UIImage = UIImage(data: imageData!)!
NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in
self.finshed!(image: image)
}
//print(self.urlString)
}
}
|
5bb44ab5527654435f0709bec6807853
| 18.615385 | 83 | 0.534314 | false | false | false | false |
apple/swift
|
refs/heads/main
|
test/IRGen/conditional-dead-strip-reflection.swift
|
apache-2.0
|
2
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -conditional-runtime-records %s -emit-ir -o %t/main.ll
// RUN: %target-clang %t/main.ll -isysroot %sdk -L%swift_obj_root/lib/swift/%target-sdk-name -flto -o %t/main
// RUN: %target-swift-reflection-dump %t/main | %FileCheck %s
// FIXME(mracek): More work needed to get this to work on non-Apple platforms.
// REQUIRES: VENDOR=apple
// For LTO, the linker dlopen()'s the libLTO library, which is a scenario that
// ASan cannot work in ("Interceptors are not working, AddressSanitizer is
// loaded too late").
// REQUIRES: no_asan
public protocol TheProtocol {
}
public class Class: TheProtocol {
}
public struct Struct {
}
public enum Enum {
}
// CHECK: FIELDS:
// CHECK: =======
// CHECK: main.TheProtocol
// CHECK: main.Class
// CHECK: main.Struct
// CHECK: main.Enum
|
aa01f4583e489f2b931cf34d560a50b2
| 26.225806 | 109 | 0.697867 | false | false | false | false |
Bouke/HAP
|
refs/heads/master
|
Sources/HAPInspector/main.swift
|
mit
|
1
|
import Foundation
var sourceURL: URL
if CommandLine.argc > 1 {
let arg = CommandLine.arguments[1]
sourceURL = URL(fileURLWithPath: arg)
} else {
let path = "/System/Library/PrivateFrameworks/HomeKitDaemon.framework"
guard let framework = Bundle(path: path) else {
print("No HomeKitDaemon private framework found")
exit(1)
}
guard let plistUrl = framework.url(forResource: "plain-metadata", withExtension: "config") else {
print("Resource plain-metadata.config not found in HomeKitDaemon.framework")
exit(1)
}
sourceURL = plistUrl
}
do {
print("Generating from \(sourceURL)")
let base = "Sources/HAP/Base"
if !FileManager.default.directoryExists(atPath: base) {
print("Expected existing directory at `\(base)`")
exit(1)
}
let target = "\(base)/Predefined"
if FileManager.default.directoryExists(atPath: target) {
try FileManager.default.removeItem(atPath: target)
}
try FileManager.default.createDirectory(atPath: target, withIntermediateDirectories: false, attributes: nil)
try inspect(source: sourceURL, target: target)
} catch {
print("Couldn't update: \(error)")
}
extension FileManager {
func directoryExists(atPath path: String) -> Bool {
var isDirectory: ObjCBool = false
let exists = fileExists(atPath: path, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
}
|
3c7ad9bd1bc6b5046f561ac8879d3a88
| 31.244444 | 112 | 0.68091 | false | false | false | false |
AlphaJian/LarsonApp
|
refs/heads/master
|
LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/WorkOrderTableView.swift
|
apache-2.0
|
1
|
//
// WorkOrderTableView.swift
// LarsonApp
//
// Created by Perry Z Chen on 11/10/16.
// Copyright © 2016 Jian Zhang. All rights reserved.
//
import UIKit
enum EnumTableViewCell: Int{
case CallNumberCell = 0
case StationCell
case SiteAddressCell
case ZipCell
case phoneNumCell
case techNumCell
case ServiceDescCell
case WorkDescCell
case AddPartsCell
case OptionCell
case SectionCount
}
class WorkOrderTableView: UITableView {
var model: AppointmentModel?
var partItems: [Int] = [Int]()
weak var vc: JobDetailViewController?
var removeItemAlertHandler: ReturnBlock?
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
self.delegate = self
self.dataSource = self
self.backgroundColor = UIColor(red: 236.0/255.0, green: 240/255.0, blue: 241/255.0, alpha: 1.0)
self.register(UINib(nibName: "StaticWorkOrderCell", bundle: nil), forCellReuseIdentifier: "StaticWorkOrderCell")
self.register(UINib(nibName: "InputWorkOrderCell", bundle: nil), forCellReuseIdentifier: "InputWorkOrderCell")
self.register(UINib(nibName: "AddPartsCell", bundle: nil), forCellReuseIdentifier: "AddPartsCell")
self.register(UINib(nibName: "PartItemCell", bundle: nil), forCellReuseIdentifier: "PartItemCell")
self.register(UINib(nibName: "WorkOrderOptionCell", bundle: nil), forCellReuseIdentifier: "WorkOrderOptionCell")
self.rowHeight = UITableViewAutomaticDimension
self.estimatedRowHeight = 60.0
self.separatorStyle = .none
// NotificationCenter.default.addObserver(self, selector: #selector(keyboardChangeFrame(notification:)), name: .UIKeyboardWilflChangeFrame, object: nil)
}
func keyboardChangeFrame(notification: Notification) {
let dicUserInfo = notification.userInfo
print(dicUserInfo?[UIKeyboardAnimationDurationUserInfoKey] ?? 48)
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
}
extension WorkOrderTableView : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == EnumTableViewCell.AddPartsCell.rawValue {
return 1 + partItems.count
} else {
return 1
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return EnumTableViewCell.SectionCount.rawValue
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == EnumTableViewCell.CallNumberCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Call Number", (self.model?.telephoneNumber)!))
return cell
} else if indexPath.section == EnumTableViewCell.StationCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Station Number", (self.model?.stationNumber)!))
return cell
} else if indexPath.section == EnumTableViewCell.SiteAddressCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Site Address", (self.model?.customerAddress)!))
return cell
} else if indexPath.section == EnumTableViewCell.ZipCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Zip Code", (self.model?.zipCode)!))
return cell
} else if indexPath.section == EnumTableViewCell.phoneNumCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Phone Number", (self.model?.telephoneNumber)!))
return cell
} else if indexPath.section == EnumTableViewCell.ServiceDescCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputWorkOrderCell", for: indexPath) as! InputWorkOrderCell
cell.initUI(parameter: ("Service Description", ""))
cell.textViewUpdateBlock = { (str: AnyObject) in
self.updateCellWithTVEdit()
}
return cell
} else if indexPath.section == EnumTableViewCell.WorkDescCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "InputWorkOrderCell", for: indexPath) as! InputWorkOrderCell
cell.initUI(parameter: ("Description of Work", ""))
cell.textViewUpdateBlock = { (str: AnyObject) in
self.updateCellWithTVEdit()
}
return cell
} else if indexPath.section == EnumTableViewCell.AddPartsCell.rawValue {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddPartsCell", for: indexPath) as! AddPartsCell
cell.initUI(parameter: ("Add Parts Used"))
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "PartItemCell", for: indexPath) as! PartItemCell
unowned let wself = self
cell.removeItemBlock = { (str: AnyObject) in
wself.showRemoveItemAlert(title: "Are you sure delete?", indexToDelete: indexPath as NSIndexPath)
}
return cell
}
} else if indexPath.section == EnumTableViewCell.OptionCell.rawValue {
let cell = tableView.dequeueReusableCell(withIdentifier: "WorkOrderOptionCell", for: indexPath) as! WorkOrderOptionCell
// cell.initUI(parameter: ("Add Parts Used"))
return cell
}
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "StaticWorkOrderCell", for: indexPath) as! StaticWorkOrderCell
cell.initUI(parameter: ("Tech Number", (self.model?.techNumber)!))
return cell
}
}
// update cell after edit textview
func updateCellWithTVEdit() {
let currentOffset = self.contentOffset
UIView.setAnimationsEnabled(false)
self.beginUpdates()
self.endUpdates()
UIView.setAnimationsEnabled(true)
self.setContentOffset(currentOffset, animated: false)
}
// 删除某个row
func showRemoveItemAlert(title: String, indexToDelete: NSIndexPath) {
let alertVC = UIAlertController(title: title, message: "", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "ok", style: .default, handler: { (alert) in
// 使用beginUpdates会crush,原因是indexpath没更新,
// http://stackoverflow.com/questions/4497925/how-to-delete-a-row-from-uitableview
// 直接用reloadData
let indexPath = NSIndexPath(row: indexToDelete.row, section: indexToDelete.section)
self.partItems.remove(at: indexPath.row-1)
self.deleteRows(at: [indexPath as IndexPath], with: .automatic)
self.reloadData()
})
let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: { (alert) in
print(alert)
})
alertVC.addAction(confirmAction)
alertVC.addAction(cancelAction)
if vc != nil {
vc?.present(alertVC, animated: true, completion: nil)
}
}
}
extension WorkOrderTableView : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == EnumTableViewCell.AddPartsCell.rawValue && indexPath.row == 0 {
self.partItems.append(1)
let indexPathItem = NSIndexPath(row: 1, section: indexPath.section)
tableView.beginUpdates()
tableView.insertRows(at: [indexPathItem as IndexPath], with: .automatic)
tableView.endUpdates()
// scroll to the item that just added
// tableView.scrollToRow(at: indexPathItem as IndexPath, at: .bottom, animated: true)
}
}
}
|
17b570c4bf35a7ad128b07689ebd543a
| 44.424084 | 159 | 0.657446 | false | false | false | false |
izeni-team/retrolux
|
refs/heads/master
|
Retrolux/Builder.swift
|
mit
|
1
|
//
// Builder.swift
// Retrolux
//
// Created by Bryan Henderson on 1/26/17.
// Copyright © 2017 Bryan. All rights reserved.
//
import Foundation
// State for each request is captured as soon as possible, instead of when it is needed.
// It is assumed that this behavior is more intuitive.
public struct RequestCapturedState {
public var base: URL
public var workerQueue: DispatchQueue
}
open class Builder {
private static let dryBase = URL(string: "e7c37c97-5483-4522-b400-106505fbf6ff/")!
open class func dry() -> Builder {
return Builder(base: self.dryBase)
}
open var base: URL
open let isDryModeEnabled: Bool
open var callFactory: CallFactory
open var client: Client
open var serializers: [Serializer]
open var requestInterceptor: ((inout URLRequest) -> Void)?
open var responseInterceptor: ((inout ClientResponse) -> Void)?
open var workerQueue = DispatchQueue(
label: "Retrolux.worker",
qos: .background,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil
)
open var stateToCapture: RequestCapturedState {
return RequestCapturedState(
base: base,
workerQueue: workerQueue
)
}
open func outboundSerializers() -> [OutboundSerializer] {
return serializers.flatMap { $0 as? OutboundSerializer }
}
open func inboundSerializers() -> [InboundSerializer] {
return serializers.flatMap { $0 as? InboundSerializer }
}
public init(base: URL) {
self.base = base
self.isDryModeEnabled = base == type(of: self).dryBase
self.callFactory = HTTPCallFactory()
self.client = HTTPClient()
self.serializers = [
ReflectionJSONSerializer(),
MultipartFormDataSerializer(),
URLEncodedSerializer()
]
self.requestInterceptor = nil
self.responseInterceptor = nil
}
open func log(request: URLRequest) {
print("Retrolux: \(request.httpMethod!) \(request.url!.absoluteString.removingPercentEncoding!)")
}
open func log<T>(response: Response<T>) {
let status = response.status ?? 0
if response.error is BuilderError == false {
let requestURL = response.request.url!.absoluteString.removingPercentEncoding!
print("Retrolux: \(status) \(requestURL)")
}
if let error = response.error {
if let localized = error as? LocalizedError {
if let errorDescription = localized.errorDescription {
print("Retrolux: Error: \(errorDescription)")
}
if let recoverySuggestion = localized.recoverySuggestion {
print("Retrolux: Suggestion: \(recoverySuggestion)")
}
if localized.errorDescription == nil && localized.recoverySuggestion == nil {
print("Retrolux: Error: \(error)")
}
} else {
print("Retrolux: Error: \(error)")
}
}
}
open func interpret<T>(response: UninterpretedResponse<T>) -> InterpretedResponse<T> {
// BuilderErrors are highest priority over other kinds of errors,
// because they represent errors creating the request.
if let error = response.error as? BuilderError {
return .failure(error)
}
if !response.isHttpStatusOk {
if response.urlResponse == nil, let error = response.error {
return .failure(ResponseError.connectionError(error))
}
return .failure(ResponseError.invalidHttpStatusCode(code: response.status))
}
if let error = response.error {
return .failure(error)
}
if let body = response.body {
return .success(body)
} else {
assert(false, "This should be impossible.")
return .failure(NSError(domain: "Retrolux.Error", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to serialize response for an unknown reason."]))
}
}
private func normalize(arg: Any, serializerType: OutboundSerializerType, serializers: [OutboundSerializer]) -> [(serializer: OutboundSerializer?, value: Any?, type: Any.Type)] {
if type(of: arg) == Void.self {
return []
} else if let wrapped = arg as? WrappedSerializerArg {
if let value = wrapped.value {
return normalize(arg: value, serializerType: serializerType, serializers: serializers)
} else {
return [(serializers.first(where: { serializerType.isDesired(serializer: $0) && $0.supports(outboundType: wrapped.type) }), nil, wrapped.type)]
}
} else if let opt = arg as? OptionalHelper {
if let value = opt.value {
return normalize(arg: value, serializerType: serializerType, serializers: serializers)
} else {
return [(serializers.first(where: { serializerType.isDesired(serializer: $0) && $0.supports(outboundType: opt.type) }), nil, opt.type)]
}
} else if arg is SelfApplyingArg {
return [(nil, arg, type(of: arg))]
} else if let serializer = serializers.first(where: { serializerType.isDesired(serializer: $0) && $0.supports(outboundType: type(of: arg)) }) {
return [(serializer, arg, type(of: arg))]
} else {
let beneath = Mirror(reflecting: arg).children.reduce([]) {
$0 + normalize(arg: $1.value, serializerType: serializerType, serializers: serializers)
}
if beneath.isEmpty {
return [(nil, arg, type(of: arg))]
} else {
return beneath
}
}
}
open func makeRequest<Args, ResponseType>(type: OutboundSerializerType = .auto, method: HTTPMethod, endpoint: String, args creationArgs: Args, response: ResponseType.Type, testProvider: ((Args, Args, URLRequest) -> ClientResponse)? = nil) -> (Args) -> Call<ResponseType> {
return { startingArgs in
var task: Task?
let enqueue: CallEnqueueFunction<ResponseType> = { (state, callback) in
var request = URLRequest(url: state.base.appendingPathComponent(endpoint))
request.httpMethod = method.rawValue
do {
try self.applyArguments(
type: type,
state: state,
endpoint: endpoint,
method: method,
creation: creationArgs,
starting: startingArgs,
modifying: &request,
responseType: response
)
self.requestInterceptor?(&request)
self.log(request: request)
if self.isDryModeEnabled {
let provider = testProvider ?? { _ in ClientResponse(data: nil, response: nil, error: nil) }
let clientResponse = provider(creationArgs, startingArgs, request)
let response = self.process(immutableClientResponse: clientResponse, request: request, responseType: ResponseType.self)
self.log(response: response)
callback(response)
} else {
task = self.client.makeAsynchronousRequest(request: &request) { (clientResponse) in
state.workerQueue.async {
let response = self.process(immutableClientResponse: clientResponse, request: request, responseType: ResponseType.self)
self.log(response: response)
callback(response)
}
}
task!.resume()
}
} catch {
let response = Response<ResponseType>(
request: request,
data: nil,
error: error,
urlResponse: nil,
body: nil,
interpreter: self.interpret
)
self.log(response: response)
callback(response)
}
}
let cancel = { () -> Void in
task?.cancel()
}
let capture = { self.stateToCapture }
return self.callFactory.makeCall(capture: capture, enqueue: enqueue, cancel: cancel)
}
}
func applyArguments<Args, ResponseType>(
type: OutboundSerializerType,
state: RequestCapturedState,
endpoint: String,
method: HTTPMethod,
creation: Args,
starting: Args,
modifying request: inout URLRequest,
responseType: ResponseType.Type
) throws
{
let outboundSerializers = self.outboundSerializers()
let normalizedCreationArgs = self.normalize(arg: creation, serializerType: type, serializers: outboundSerializers) // Args used to create this request
let normalizedStartingArgs = self.normalize(arg: starting, serializerType: type, serializers: outboundSerializers) // Args passed in when executing this request
assert(normalizedCreationArgs.count == normalizedStartingArgs.count)
var selfApplying: [BuilderArg] = []
var serializer: OutboundSerializer?
var serializerArgs: [BuilderArg] = []
for (creation, starting) in zip(normalizedCreationArgs, normalizedStartingArgs) {
assert((creation.serializer != nil) == (starting.serializer != nil), "Somehow normalize failed to produce the same results on both sides.")
assert(creation.serializer == nil || creation.serializer === starting.serializer, "Normalize didn't produce the same serializer on both sides.")
let arg = BuilderArg(type: creation.type, creation: creation.value, starting: starting.value)
if creation.type is SelfApplyingArg.Type {
selfApplying.append(arg)
} else if let thisSerializer = creation.serializer {
if serializer == nil {
serializer = thisSerializer
} else {
// Serializer already set
}
serializerArgs.append(arg)
} else {
throw BuilderError.unsupportedArgument(arg)
}
}
if let serializer = serializer {
do {
try serializer.apply(arguments: serializerArgs, to: &request)
} catch {
throw BuilderError.serializationError(serializer: serializer, error: error, arguments: serializerArgs)
}
}
for arg in selfApplying {
let type = arg.type as! SelfApplyingArg.Type
type.apply(arg: arg, to: &request)
}
}
func process<ResponseType>(immutableClientResponse: ClientResponse, request: URLRequest, responseType: ResponseType.Type) -> Response<ResponseType> {
var clientResponse = immutableClientResponse
self.responseInterceptor?(&clientResponse)
let body: ResponseType?
let error: Error?
if let error = clientResponse.error {
let response = Response<ResponseType>(
request: request,
data: clientResponse.data,
error: error,
urlResponse: clientResponse.response,
body: nil,
interpreter: self.interpret
)
return response
}
if ResponseType.self == Void.self {
body = (() as! ResponseType)
error = nil
} else {
if let serializer = inboundSerializers().first(where: { $0.supports(inboundType: ResponseType.self) }) {
do {
body = try serializer.makeValue(from: clientResponse, type: ResponseType.self)
error = nil
} catch let serializerError {
body = nil
error = BuilderResponseError.deserializationError(serializer: serializer, error: serializerError, clientResponse: clientResponse)
}
} else {
// This is incorrect usage of Retrolux, hence it is a fatal error.
fatalError("Unsupported argument type when processing request: \(ResponseType.self)")
}
}
let response: Response<ResponseType> = Response(
request: request,
data: clientResponse.data,
error: error ?? clientResponse.error,
urlResponse: clientResponse.response,
body: body,
interpreter: self.interpret
)
return response
}
}
|
abbad699c6d00d706d2978ccc96d68a0
| 40.623053 | 276 | 0.559015 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Source/Core/Code/RegistrationAPI.swift
|
apache-2.0
|
2
|
//
// RegistrationAPI.swift
// edX
//
// Created by Akiva Leffert on 3/14/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
class RegistrationAPIError : NSError {
struct Field {
let userMessage: String
}
let fieldInfo : [String:Field]
init(fields: [String:Field]) {
self.fieldInfo = fields
super.init(domain: "org.edx.mobile.registration", code: -1, userInfo: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public struct RegistrationAPI {
static func registrationDeserializer(_ response : HTTPURLResponse, json: JSON) -> Result<()> {
if response.httpStatusCode.is2xx {
return .success(())
}
else if response.httpStatusCode == OEXHTTPStatusCode.code400BadRequest {
var fields: [String:RegistrationAPIError.Field] = [:]
for (key, value) in json.dictionaryValue {
if let message = value.array?.first?["user_message"].string {
fields[key] = RegistrationAPIError.Field(userMessage: message)
}
}
return .failure(RegistrationAPIError(fields: fields))
}
return .failure(NetworkManager.unknownError)
}
// Registers a new user
public static func registrationRequest(fields: [String:String]) -> NetworkRequest<()> {
return NetworkRequest(
method: .POST,
path: "/user_api/v1/account/registration/",
body: .formEncoded(fields),
deserializer: .jsonResponse(registrationDeserializer))
}
}
|
772af17a6696ad5fd83048a7086ada5f
| 28.696429 | 98 | 0.614552 | false | false | false | false |
andrewcar/hoods
|
refs/heads/master
|
Project/hoods/hoods/ProfileView.swift
|
mit
|
1
|
//
// ProfileView.swift
// hoods
//
// Created by Andrew Carvajal on 6/19/18.
// Copyright © 2018 YugeTech. All rights reserved.
//
import UIKit
import UIImageColors
class ProfileView: UIView {
var closedProfileConstraints = [NSLayoutConstraint]()
var openProfileConstraints = [NSLayoutConstraint]()
var profileImageView = UIImageView()
var nameLabel = UILabel()
var button = UIButton()
var swipe = UISwipeGestureRecognizer()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
layer.cornerRadius = frame.width / 2
layer.masksToBounds = true
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.image = UIImage(named: "profile_placeholder")
profileImageView.layer.cornerRadius = (frame.width - 4) / 2
profileImageView.layer.masksToBounds = true
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.numberOfLines = 1
nameLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 100)
nameLabel.adjustsFontSizeToFitWidth = true
nameLabel.textAlignment = .center
nameLabel.baselineAdjustment = .alignCenters
nameLabel.textColor = .reptileGreen
nameLabel.text = " "
button.translatesAutoresizingMaskIntoConstraints = false
swipe.direction = .down
addSubview(profileImageView)
addSubview(nameLabel)
addSubview(button)
addGestureRecognizer(swipe)
}
func activateClosedConstraints(_ viewWidth: CGFloat) {
NSLayoutConstraint.deactivate(closedProfileConstraints)
NSLayoutConstraint.deactivate(openProfileConstraints)
closedProfileConstraints = [
profileImageView.topAnchor.constraint(equalTo: topAnchor, constant: 2),
profileImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 2),
profileImageView.widthAnchor.constraint(equalToConstant: viewWidth - 4),
profileImageView.heightAnchor.constraint(equalToConstant: viewWidth - 4),
nameLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor),
nameLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor),
nameLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor),
nameLabel.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor),
button.topAnchor.constraint(equalTo: topAnchor),
button.leftAnchor.constraint(equalTo: leftAnchor),
button.rightAnchor.constraint(equalTo: rightAnchor),
button.bottomAnchor.constraint(equalTo: bottomAnchor),
]
NSLayoutConstraint.activate(closedProfileConstraints)
}
func activateOpenConstraints(_ viewWidth: CGFloat) {
NSLayoutConstraint.deactivate(closedProfileConstraints)
NSLayoutConstraint.deactivate(openProfileConstraints)
let width = (viewWidth * 0.5) - (Frames.si.padding * 1.5)
openProfileConstraints = [
profileImageView.topAnchor.constraint(equalTo: topAnchor, constant: Frames.si.padding * 3),
profileImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: Frames.si.padding),
profileImageView.widthAnchor.constraint(equalToConstant: width),
profileImageView.heightAnchor.constraint(equalToConstant: width),
nameLabel.topAnchor.constraint(equalTo: topAnchor, constant: Frames.si.padding * 3),
nameLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: (Frames.si.padding * 2) + width),
nameLabel.widthAnchor.constraint(equalToConstant: width),
nameLabel.heightAnchor.constraint(equalToConstant: width),
button.topAnchor.constraint(equalTo: topAnchor),
button.leftAnchor.constraint(equalTo: leftAnchor),
button.rightAnchor.constraint(equalTo: leftAnchor),
button.bottomAnchor.constraint(equalTo: topAnchor)
]
NSLayoutConstraint.activate(openProfileConstraints)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
a8ddc5f866947f207538de82e392fbac
| 39.684211 | 108 | 0.67486 | false | false | false | false |
kasei/kineo
|
refs/heads/master
|
Sources/Kineo/SPARQL/MaterializedQueryPlan.swift
|
mit
|
1
|
//
// MaterializedQueryPlan.swift
// Kineo
//
// Created by Gregory Todd Williams on 6/6/20.
//
import Foundation
import SPARQLSyntax
public struct MaterializeTermsPlan: NullaryQueryPlan {
public var idPlan: IDQueryPlan
var store: LazyMaterializingQuadStore
var verbose: Bool
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var isJoinIdentity: Bool { return false }
public var isUnionIdentity: Bool { return false }
public var selfDescription: String {
return "Materialize Terms"
}
public func serialize(depth: Int=0) -> String {
let indent = String(repeating: " ", count: (depth*2))
let name = self.selfDescription
var d = "\(indent)\(name)\n"
d += idPlan.serialize(depth: depth+1)
return d
}
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try idPlan.evaluate(metrics)
// var seen = Set<UInt64>()
// let verbose = self.verbose
let s = i.lazy.map { (r) -> SPARQLResultSolution<Term>? in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
do {
let d = try r.map { (pair) -> (String, Term)? in
let tid = pair.value
guard let term = try self.store.term(from: tid) else { return nil }
// if verbose {
// if !seen.contains(tid) {
// print("materializing [\(tid)] \(term)")
// seen.insert(tid)
// }
// }
return (pair.key, term)
}
let bindings = Dictionary(uniqueKeysWithValues: d.compactMap { $0 })
return SPARQLResultSolution<Term>(bindings: bindings)
} catch {
return nil
}
}
let results = s.lazy.compactMap { $0 }
return AnyIterator(results.makeIterator())
}
}
public struct RestrictToNamedGraphsPlan<Q: QuadStoreProtocol>: UnaryQueryPlan {
public var child: QueryPlan
public var metricsToken: QueryPlanEvaluationMetrics.Token
var project: Set<String>
var graphNode: Node
var graphName: String
var store: Q
var dataset: DatasetProtocol
init(child: QueryPlan, project: Set<String>, rewriteGraphFrom: Node, to rewriteGraphTo: String, store: Q, dataset: DatasetProtocol, metricsToken: QueryPlanEvaluationMetrics.Token) {
self.child = child
self.project = project.union([rewriteGraphTo])
self.graphNode = rewriteGraphFrom
self.graphName = rewriteGraphTo
self.store = store
self.dataset = dataset
self.metricsToken = metricsToken
}
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let graphFilter = { (g: Term) -> Bool in
return (try? self.dataset.isGraphNamed(g, in: self.store)) ?? false
}
var okGraph = Set<Term>()
let i = try child.evaluate(metrics)
let s = i.lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
if let g = r[graphNode] {
do {
if okGraph.contains(g) {
var rr = r.projected(variables: project)
try rr.extend(variable: graphName, value: g)
return rr
} else if graphFilter(g) {
okGraph.insert(g)
var rr = r.projected(variables: project)
try rr.extend(variable: graphName, value: g)
return rr
}
} catch {}
}
return nil
}
return AnyIterator(s.makeIterator())
}
public func serialize(depth: Int=0) -> String {
let indent = String(repeating: " ", count: (depth*2))
let name = "RestrictToNamedGraphs [ rewriting: ?\(graphName) ← \(graphNode) ]"
var d = "\(indent)\(name)\n"
for c in self.properties {
d += c.serialize(depth: depth+1)
}
for c in self.children {
d += c.serialize(depth: depth+1)
}
return d
}
}
public struct TablePlan: NullaryQueryPlan, QueryPlanSerialization {
var columns: [Node]
var rows: [[Term?]]
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var isJoinIdentity: Bool {
guard rows.count == 1 else { return false }
guard columns.count == 0 else { return false }
return true
}
public var isUnionIdentity: Bool {
return rows.count == 0
}
public var selfDescription: String { return "Table { \(columns) ; \(rows.count) rows }" }
public static var joinIdentity = TablePlan(columns: [], rows: [[]], metricsToken: QueryPlanEvaluationMetrics.silentToken)
public static var unionIdentity = TablePlan(columns: [], rows: [], metricsToken: QueryPlanEvaluationMetrics.silentToken)
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
var results = [SPARQLResultSolution<Term>]()
for row in rows {
var bindings = [String:Term]()
for (node, term) in zip(columns, row) {
guard case .variable(let name, _) = node else {
Logger.shared.error("Unexpected variable generated during table evaluation")
throw QueryError.evaluationError("Unexpected variable generated during table evaluation")
}
if let term = term {
bindings[name] = term
}
}
let result = SPARQLResultSolution<Term>(bindings: bindings)
results.append(result)
}
return AnyIterator(results.makeIterator())
}
}
public struct QuadPlan: NullaryQueryPlan, QueryPlanSerialization {
var quad: QuadPattern
var store: QuadStoreProtocol
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Quad(\(quad))" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
return try store.results(matching: quad)
}
public var isJoinIdentity: Bool { return false }
public var isUnionIdentity: Bool { return false }
}
public struct NestedLoopJoinPlan: BinaryQueryPlan, QueryPlanSerialization {
public var lhs: QueryPlan
public var rhs: QueryPlan
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Nested Loop Join" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let l = try Array(lhs.evaluate(metrics))
let r = try rhs.evaluate(metrics)
var results = [SPARQLResultSolution<Term>]()
for rresult in r {
for lresult in l {
if let j = lresult.join(rresult) {
results.append(j)
}
}
}
return AnyIterator(results.makeIterator())
}
}
enum HashJoinType {
case inner
case outer
case anti
}
func _lexicographicallyPrecedes<T: Comparable> (lhs: [T?], rhs: [T?]) -> Bool {
for (l, r) in zip(lhs, rhs) {
switch (l, r) {
case let (a, b) where a == b:
break
case (nil, _):
return true
case (_, nil):
return false
case let (.some(l), .some(r)):
return l < r
}
}
return false
}
// Requires that the iterators be lexicographically sorted by the bindings corresponding to the named (ordered) variables
func mergeJoin<I: IteratorProtocol, J: IteratorProtocol, T>(_ lhs: I, _ rhs: J, variables: [String]) -> AnyIterator<I.Element> where I.Element == SPARQLResultSolution<T>, I.Element == J.Element {
var i = PeekableIterator(generator: lhs)
var j = PeekableIterator(generator: rhs)
var buffer = [SPARQLResultSolution<T>]()
return AnyIterator {
repeat {
if let i = buffer.popLast() {
return i
}
guard let lr = i.peek() else {
return nil
}
guard let rr = j.peek() else {
return nil
}
let lkey = variables.map { lr[$0] }
let rkey = variables.map { rr[$0] }
if lkey == rkey {
// there is some data that joins
// pull all the matching rows from both sides, and find the compatible results from the cartesian product
var lresults = [i.next()!]
while let lr = i.peek() {
let lnextkey = variables.map { lr[$0] }
if lkey == lnextkey {
lresults.append(i.next()!)
} else {
break
}
}
var rresults = [j.next()!]
while let rr = j.peek() {
let rnextkey = variables.map { rr[$0] }
if rkey == rnextkey {
rresults.append(j.next()!)
} else {
break
}
}
// this is just a nested loop join. if either of the operands is large,
// might consider using the hash join implementation to produce these results
for lhs in lresults {
for rhs in rresults {
if let j = lhs.join(rhs) {
buffer.append(j)
}
}
}
} else if _lexicographicallyPrecedes(lhs: lkey, rhs: rkey) {
i.next()
} else {
j.next()
}
} while true
}
}
func hashJoin<I: IteratorProtocol, J: IteratorProtocol, T>(_ lhs: I, _ rhs: J, joinVariables: Set<String>, type: HashJoinType = .inner, metrics: QueryPlanEvaluationMetrics, token: QueryPlanEvaluationMetrics.Token) -> AnyIterator<I.Element> where I.Element == SPARQLResultSolution<T>, I.Element == J.Element {
metrics.resumeEvaluation(token: token)
defer { metrics.endEvaluation(token) }
var table = [I.Element: [I.Element]]()
var unboundTable = [I.Element]()
// warn(">>> filling hash table")
var count = 0
let r = AnySequence { return rhs }
for result in r {
count += 1
let key = result.projected(variables: joinVariables)
if key.keys.count != joinVariables.count {
unboundTable.append(result)
} else {
table[key, default: []].append(result)
}
}
// warn(">>> done (\(count) results in \(Array(table.keys).count) buckets)")
var buffer = [SPARQLResultSolution<T>]()
var l = lhs
return AnyIterator {
metrics.resumeEvaluation(token: token)
defer { metrics.endEvaluation(token) }
repeat {
if buffer.count > 0 {
let r = buffer.remove(at: 0)
return r
}
guard let result = l.next() else { return nil }
let key = result.projected(variables: joinVariables)
var buckets = [SPARQLResultSolution<T>]()
if key.keys.count != joinVariables.count {
for bucket in table.keys {
if let _ = bucket.join(result) {
buckets.append(bucket)
}
}
} else {
buckets.append(key)
}
var seen = false
for bucket in buckets {
if let results = table[bucket] {
for lhs in results {
if let j = lhs.join(result) {
seen = true
if type != .anti {
buffer.append(j)
}
}
}
}
}
for lhs in unboundTable {
if let j = lhs.join(result) {
seen = true
if type != .anti {
buffer.append(j)
}
}
}
if type == .outer && !seen {
buffer.append(result)
} else if type == .anti && !seen {
buffer.append(result)
}
} while true
}
}
public struct HashJoinPlan: BinaryQueryPlan, QueryPlanSerialization {
public var lhs: QueryPlan
public var rhs: QueryPlan
var joinVariables: Set<String>
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Hash Join { \(joinVariables) }" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let joinVariables = self.joinVariables
let l = try lhs.evaluate(metrics)
let r = try rhs.evaluate(metrics)
return hashJoin(l, r, joinVariables: joinVariables, metrics: metrics, token: metricsToken)
}
}
public struct UnionPlan: BinaryQueryPlan, QueryPlanSerialization {
public var lhs: QueryPlan
public var rhs: QueryPlan
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Union" }
public init(lhs: QueryPlan, rhs: QueryPlan, metricsToken: QueryPlanEvaluationMetrics.Token) {
self.lhs = lhs
self.rhs = rhs
self.metricsToken = metricsToken
}
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let l = try lhs.evaluate(metrics)
let r = try rhs.evaluate(metrics)
var lok = true
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
if lok, let ll = l.next() {
return ll
} else {
lok = false
return r.next()
}
// TODO: this simplified version should work but breaks due to a bug in the SQLite bindings that make repeated calls to next() after end-of-iterator throw an error
// return l.next() ?? r.next()
}
return i
}
}
public struct FilterPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var expression: Expression
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Filter \(expression)" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try child.evaluate(metrics)
let expression = self.expression
let evaluator = self.evaluator
let s = i.lazy.filter { (r) -> Bool in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
// evaluator.nextResult()
do {
let term = try evaluator.evaluate(expression: expression, result: r)
let e = try term.ebv()
return e
} catch {
return false
}
}
return AnyIterator(s.makeIterator())
}
}
public struct DiffPlan: BinaryQueryPlan, QueryPlanSerialization {
public var lhs: QueryPlan
public var rhs: QueryPlan
var expression: Expression
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Diff \(expression)" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try lhs.evaluate(metrics)
let r = try Array(rhs.evaluate(metrics))
let evaluator = self.evaluator
let expression = self.expression
return AnyIterator {
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
repeat {
guard let result = i.next() else { return nil }
var ok = true
for candidate in r {
if let j = result.join(candidate) {
evaluator.nextResult()
if let term = try? evaluator.evaluate(expression: expression, result: j) {
if case .some(true) = try? term.ebv() {
ok = false
break
}
}
}
}
if ok {
return result
}
} while true
}
}
}
public struct ExtendPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var expression: Expression
var variable: String
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Extend ?\(variable) ← \(expression)" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try child.evaluate(metrics)
let expression = self.expression
let evaluator = self.evaluator
let variable = self.variable
let s = i.lazy.map { (r) -> SPARQLResultSolution<Term> in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
// evaluator.nextResult()
do {
let term = try evaluator.evaluate(expression: expression, result: r)
return r.extended(variable: variable, value: term) ?? r
} catch {
return r
}
}
return AnyIterator(s.makeIterator())
}
}
public struct NextRowPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Next Row" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try child.evaluate(metrics)
let evaluator = self.evaluator
let s = i.lazy.map { (r) -> SPARQLResultSolution<Term> in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
evaluator.nextResult()
return r
}
return AnyIterator(s.makeIterator())
}
}
public struct MinusPlan: BinaryQueryPlan, QueryPlanSerialization {
public var lhs: QueryPlan
public var rhs: QueryPlan
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Minus" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let l = try lhs.evaluate(metrics)
let r = try Array(rhs.evaluate(metrics))
return AnyIterator {
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
while true {
var candidateOK = true
guard let candidate = l.next() else { return nil }
for result in r {
let domainIntersection = Set(candidate.keys).intersection(result.keys)
let disjoint = (domainIntersection.count == 0)
let compatible = !(candidate.join(result) == nil)
if !(disjoint || !compatible) {
candidateOK = false
break
}
}
if candidateOK {
return candidate
}
}
}
}
}
public struct ProjectPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var variables: Set<String>
public var metricsToken: QueryPlanEvaluationMetrics.Token
public init(child: QueryPlan, variables: Set<String>, metricsToken: QueryPlanEvaluationMetrics.Token) {
self.child = child
self.variables = variables
self.metricsToken = metricsToken
}
public var selfDescription: String { return "Project { \(variables.sorted().joined(separator: ", ")) }" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let vars = self.variables
let s = try child.evaluate(metrics).lazy.map {$0.projected(variables: vars) }
return AnyIterator(s.makeIterator())
}
}
public struct LimitPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var limit: Int
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Limit { \(limit) }" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let s = try child.evaluate(metrics).prefix(limit)
return AnyIterator(s.makeIterator())
}
}
public struct OffsetPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var offset: Int
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Offset { \(offset) }" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let s = try child.evaluate(metrics).lazy.dropFirst(offset)
return AnyIterator(s.makeIterator())
}
}
public struct DistinctPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Distinct" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
var seen = Set<SPARQLResultSolution<Term>>()
let s = try child.evaluate(metrics).lazy.filter { (r) -> Bool in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
if seen.contains(r) {
return false
} else {
seen.insert(r)
return true
}
}
return AnyIterator(s.makeIterator())
}
}
public struct ReducedPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Distinct" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
var last: SPARQLResultSolution<Term>? = nil
let s = try child.evaluate(metrics).lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
if let l = last, l == r {
return nil
}
last = r
return r
}
return AnyIterator(s.makeIterator())
}
}
public struct ServicePlan: NullaryQueryPlan, QueryPlanSerialization {
var endpoint: URL
var query: String
var silent: Bool
var client: SPARQLClient
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var isJoinIdentity: Bool { return false }
public var isUnionIdentity: Bool { return false }
public init(endpoint: URL, query: String, silent: Bool, client: SPARQLClient, metricsToken: QueryPlanEvaluationMetrics.Token) {
self.endpoint = endpoint
self.query = query
self.silent = silent
self.client = client
self.metricsToken = metricsToken
}
public var selfDescription: String { return "Service \(silent ? "Silent " : "")<\(endpoint)>: \(query)" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
do {
let r = try client.execute(query)
switch r {
case let .bindings(_, seq):
return AnyIterator(seq.makeIterator())
default:
throw QueryError.evaluationError("SERVICE request did not return bindings")
}
} catch let e {
throw QueryError.evaluationError("SERVICE error: \(e)")
}
}
}
public struct OrderPlan: UnaryQueryPlan, QueryPlanSerialization {
fileprivate struct SortElem {
var result: SPARQLResultSolution<Term>
var terms: [Term?]
}
public var child: QueryPlan
var comparators: [Algebra.SortComparator]
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Order { \(comparators) }" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let evaluator = self.evaluator
let results = try Array(child.evaluate(metrics))
let elements = results.map { (r) -> SortElem in
let terms = comparators.map { (cmp) in
try? evaluator.evaluate(expression: cmp.expression, result: r)
}
return SortElem(result: r, terms: terms)
}
let sorted = elements.sorted { (a, b) -> Bool in
let pairs = zip(a.terms, b.terms)
for (cmp, pair) in zip(comparators, pairs) {
guard let lhs = pair.0 else { return true }
guard let rhs = pair.1 else { return false }
if lhs == rhs {
continue
}
var sorted = lhs < rhs
if !cmp.ascending {
sorted = !sorted
}
return sorted
}
return false
}
return AnyIterator(sorted.map { $0.result }.makeIterator())
}
}
private extension Array {
init<I: IteratorProtocol>(consuming i: inout I, limit: Int? = nil) where I.Element == Element {
if limit == .some(0) {
self = []
return
}
var buffer = [I.Element]()
while let item = i.next() {
buffer.append(item)
if let l = limit, buffer.count >= l {
break
}
}
self = buffer
}
}
public struct WindowPlan: UnaryQueryPlan, QueryPlanSerialization {
// NOTE: WindowPlan assumes the child plan is sorted in the expected order of the window application's partitioning and sort comparators
public var child: QueryPlan
var function: Algebra.WindowFunctionMapping
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String {
return "Window \(function.description))"
}
private func partition<I: IteratorProtocol>(_ results: I, by partition: [Expression]) -> AnyIterator<AnyIterator<SPARQLResultSolution<Term>>> where I.Element == SPARQLResultSolution<Term> {
let ee = evaluator
let seq = AnySequence { return results }
let withGroups = seq.lazy.map { (r) -> (SPARQLResultSolution<Term>, [Term?]) in
let group = partition.map { try? ee.evaluate(expression: $0, result: r) }
return (r, group)
}
var buffer = [SPARQLResultSolution<Term>]()
var currentGroup = [Term?]()
var i = withGroups.makeIterator()
let grouped = AnyIterator { () -> AnyIterator<SPARQLResultSolution<Term>>? in
while true {
guard let pair = i.next() else {
if buffer.isEmpty {
return nil
} else {
let b = buffer
buffer = []
return AnyIterator(b.makeIterator())
}
}
let r = pair.0
let g = pair.1
if g != currentGroup {
currentGroup = g
if !buffer.isEmpty {
let b = buffer
buffer = [r]
return AnyIterator(b.makeIterator())
}
}
buffer.append(r)
}
}
return grouped
}
private func comparisonTerms(from term: SPARQLResultSolution<Term>, using comparators: [Algebra.SortComparator]) -> [Term?] {
let terms = comparators.map { (cmp) -> Term? in
return try? evaluator.evaluate(expression: cmp.expression, result: term)
}
return terms
}
private func resultsAreEqual(_ a : SPARQLResultSolution<Term>, _ b : SPARQLResultSolution<Term>, usingComparators comparators: [Algebra.SortComparator]) -> Bool {
if comparators.isEmpty {
return a == b
}
for cmp in comparators {
guard var lhs = try? evaluator.evaluate(expression: cmp.expression, result: a) else { return true }
guard var rhs = try? evaluator.evaluate(expression: cmp.expression, result: b) else { return false }
if !cmp.ascending {
(lhs, rhs) = (rhs, lhs)
}
if lhs < rhs {
return false
} else if lhs > rhs {
return false
}
}
return true
}
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let app = function.windowApplication
let group = app.partition
let results = try child.evaluate(metrics)
let partitionGroups = partition(results, by: group)
let v = function.variableName
let frame = app.frame
guard frame.type == .rows else {
throw QueryPlanError.unimplemented("RANGE window frames are not implemented")
}
switch app.windowFunction {
case .rank, .denseRank:
// RANK ignores any specified window frame
let order = app.comparators
let groups = AnySequence(partitionGroups).lazy.map { (g) -> [SPARQLResultSolution<Term>] in
var rank = 0
var increment = 1
var last: SPARQLResultSolution<Term>? = nil
let groupResults = g.map { (r) -> SPARQLResultSolution<Term> in
if let last = last {
if !self.resultsAreEqual(last, r, usingComparators: order) {
rank += increment
increment = 1
} else if app.windowFunction == .rank {
increment += 1
}
} else {
rank += increment
}
last = r
let rr = r.extended(variable: v, value: Term(integer: rank)) ?? r
return rr
}
return groupResults
}
let groupsResults = groups.lazy.flatMap { $0 }
return AnyIterator(groupsResults.makeIterator())
case .rowNumber:
// ROW_NUMBER ignores any specified window frame
let groups = AnySequence(partitionGroups).lazy.map { (g) -> [SPARQLResultSolution<Term>] in
let groupResults = g.lazy.enumerated().map { (i, r) -> SPARQLResultSolution<Term> in
let rr = r.extended(variable: v, value: Term(integer: i+1)) ?? r
return rr
}
return groupResults
}
let groupsResults = groups.flatMap { $0 }
return AnyIterator(groupsResults.makeIterator())
case .ntile(let n):
// NTILE ignores any specified window frame
let order = app.comparators
let groups = AnySequence(partitionGroups).lazy.map { (g) -> [SPARQLResultSolution<Term>] in
let sorted = Array(g)
let peerGroupsCount = Set(sorted.map { self.comparisonTerms(from: $0, using: order) }).count
let nSize = peerGroupsCount / n
let nLarge = peerGroupsCount - n*nSize
let iSmall = nLarge * (nSize+1)
var last: SPARQLResultSolution<Term>? = nil
var groupResults = [SPARQLResultSolution<Term>]()
var iRow = -1
for r in sorted {
if let last = last {
if !self.resultsAreEqual(last, r, usingComparators: order) {
iRow += 1
}
} else {
iRow += 1
}
last = r
let q: Int
if iRow < iSmall {
q = 1 + iRow/(nSize+1)
} else {
q = 1 + nLarge + (iRow-iSmall)/nSize
}
let rr = r.extended(variable: v, value: Term(integer: q)) ?? r
groupResults.append(rr)
}
return groupResults
}
let groupsResults = groups.flatMap { $0 }
return AnyIterator(groupsResults.makeIterator())
case .aggregation(let agg):
let frame = app.frame
let seq = AnySequence(partitionGroups)
let groups = try seq.lazy.map { (g) -> [SPARQLResultSolution<Term>] in
let impl = windowAggregation(agg)
let groupResults = try impl.evaluate(
g,
frame: frame,
variableName: v,
evaluator: evaluator
)
return Array(groupResults)
}
let groupsResults = groups.flatMap { $0 }
return AnyIterator(groupsResults.makeIterator())
case .custom(_, _):
throw QueryPlanError.unimplemented("Extension window functions are not supported")
}
/**
For each group:
* Buffer each SPARQLResultSolution<Term> in the group
* create a sequence that will emit a Sequence<SPARQLResultSolution<Term>> with the window value
* zip the group buffer and the window sequence, produing a joined result sequence
Return the concatenation of each group's zipped result sequence
**/
}
struct SlidingWindowImplementation {
var add: (SPARQLResultSolution<Term>) -> ()
var remove: (SPARQLResultSolution<Term>) -> ()
var value: () -> Term?
func evaluate<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
// This is broken down into several different methods that each implement
// a different frame bound type (e.g. anything to current row, anything
// from current row, unbounded/preceding(n) to preceding(m), etc.)
// It's likely that these could be combined into fewer distinct methods
// and be implemented more efficiently in the future.
switch (frame.from, frame.to) {
case (_, .current):
return try evaluateToCurrent(group, frame: frame, variableName: variableName, evaluator: evaluator)
case (.current, _):
return try evaluateFromCurrent(group, frame: frame, variableName: variableName, evaluator: evaluator)
case (.unbound, .unbound):
return try evaluateComplete(group, frame: frame, variableName: variableName, evaluator: evaluator)
case (.unbound, .preceding(let tpe)), (.preceding(_), .preceding(let tpe)):
return try evaluateToPreceding(group, frame: frame, variableName: variableName, evaluator: evaluator, bound: tpe)
case (.following(let ffe), .unbound), (.following(let ffe), .following(_)):
return try evaluateFromFollowing(group, frame: frame, variableName: variableName, evaluator: evaluator, bound: ffe)
case (.unbound, .following(let tfe)), (.preceding(_), .following(let tfe)):
return try evaluateToFollowing(group, frame: frame, variableName: variableName, evaluator: evaluator, bound: tfe)
case (.preceding(let fpe), .unbound):
return try evaluateFromPrecedingToUnbounded(group, frame: frame, variableName: variableName, evaluator: evaluator, bound: fpe)
case (_, .preceding(_)), (.following(_), _):
throw QueryPlanError.invalidExpression
}
}
func evaluateComplete<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
var group = group
var buffer = Array(consuming: &group)
buffer.forEach { self.add($0) }
let value = self.value()
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard !buffer.isEmpty else { return nil }
let r = buffer.removeFirst()
var result = r
if let v = value {
result = result.extended(variable: variableName, value: v) ?? result
}
return result
}
return i
}
func evaluateFromFollowing<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator, bound toPrecedingExpression: Expression) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
let fflt = try evaluator.evaluate(expression: toPrecedingExpression, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let ffln = fflt.numeric else {
throw QueryPlanError.nonConstantExpression
}
let fromFollowingLimit = Int(ffln.value)
var toFollowingLimit: Int? = nil
switch frame.to {
case .following(let expr):
let t = try evaluator.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = t.numeric else {
throw QueryPlanError.nonConstantExpression
}
toFollowingLimit = Int(n.value)
default:
break
}
var group = group
if let toFollowingLimit = toFollowingLimit {
// BETWEEN $fromFollowingLimit AND $toFollowingLimit
let buffer = Array(consuming: &group)
buffer.prefix(1+toFollowingLimit).forEach { self.add($0) }
var windowEndIndex = buffer.index(buffer.startIndex, offsetBy: toFollowingLimit)
var window = Array(buffer.prefix(upTo: buffer.index(after: windowEndIndex)))
for _ in 0..<fromFollowingLimit {
guard !window.isEmpty else { break }
let rr = window.removeFirst()
self.remove(rr)
}
let seq = buffer.map { (r) ->SPARQLResultSolution<Term> in
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
if !window.isEmpty {
let rr = window.removeFirst()
self.remove(rr)
if windowEndIndex != buffer.endIndex {
windowEndIndex = buffer.index(after: windowEndIndex)
if windowEndIndex != buffer.endIndex {
let r = buffer[windowEndIndex]
window.append(r)
self.add(r)
}
}
}
return result
}
return AnyIterator(seq.makeIterator())
} else {
// BETWEEN $fromFollowingLimit AND UNBOUNDED
let buffer = Array(consuming: &group)
buffer.forEach { self.add($0) }
var window = buffer
for _ in 0..<fromFollowingLimit {
guard !window.isEmpty else { break }
let rr = window.removeFirst()
self.remove(rr)
}
let seq = buffer.map { (r) ->SPARQLResultSolution<Term> in
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
if !window.isEmpty {
self.remove(window.removeFirst())
}
return result
}
return AnyIterator(seq.makeIterator())
}
}
func evaluateToPreceding<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator, bound toPrecedingExpression: Expression) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
let tplt = try evaluator.evaluate(expression: toPrecedingExpression, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let tpln = tplt.numeric else {
throw QueryPlanError.nonConstantExpression
}
let toPrecedingLimit = Int(tpln.value)
var fromPrecedingLimit: Int? = nil
switch frame.from {
case .preceding(let expr):
let t = try evaluator.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = t.numeric else {
throw QueryPlanError.nonConstantExpression
}
fromPrecedingLimit = Int(n.value)
default:
break
}
var group = group
var buffer = [SPARQLResultSolution<Term>]()
var window = [SPARQLResultSolution<Term>]()
var count = 0
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard let r = group.next() else { return nil }
buffer.append(r)
if let fromPrecedingLimit = fromPrecedingLimit {
// BETWEEN $fromPrecedingLimit AND $toPrecedingLimit
if count > fromPrecedingLimit {
let r = window.removeFirst()
self.remove(r)
}
} else {
// BETWEEN UNBOUNDED AND $toPrecedingLimit
}
if buffer.count > toPrecedingLimit {
let r = buffer.removeFirst()
self.add(r)
window.append(r)
}
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
count += 1
return result
}
return i
}
func evaluateFromPrecedingToUnbounded<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator, bound fromPrecedingExpression: Expression) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
let fplt = try evaluator.evaluate(expression: fromPrecedingExpression, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let fpln = fplt.numeric else {
throw QueryPlanError.nonConstantExpression
}
let fromPrecedingLimit = Int(fpln.value)
var group = group
var buffer = Array(consuming: &group)
var window = buffer
buffer.forEach { self.add($0) }
var count = 0
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard !buffer.isEmpty else { return nil }
let r = buffer.removeFirst()
if count > fromPrecedingLimit {
let rr = window.removeFirst()
self.remove(rr)
}
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
count += 1
return result
}
return i
}
func evaluateToFollowing<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator, bound toPrecedingExpression: Expression) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
let tflt = try evaluator.evaluate(expression: toPrecedingExpression, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let tfln = tflt.numeric else {
throw QueryPlanError.nonConstantExpression
}
let toFollowingLimit = Int(tfln.value)
var fromPrecedingLimit: Int? = nil
switch frame.from {
case .preceding(let expr):
let t = try evaluator.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = t.numeric else {
throw QueryPlanError.nonConstantExpression
}
fromPrecedingLimit = Int(n.value)
default:
break
}
var group = group
var buffer = Array(consuming: &group, limit: 1+toFollowingLimit)
var window = buffer.prefix(1+toFollowingLimit)
buffer.forEach { self.add($0) }
var count = 0
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard !buffer.isEmpty else { return nil }
let r = buffer.removeFirst()
if let fromPrecedingLimit = fromPrecedingLimit {
// BETWEEN $fromPrecedingLimit AND $toFollowingLimit FOLLOWING
if count > fromPrecedingLimit {
let rr = window.removeFirst()
self.remove(rr)
}
} else {
// BETWEEN UNBOUNDED AND $toFollowingLimit FOLLOWING
}
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
if let rr = group.next() {
window.append(rr)
buffer.append(rr)
self.add(rr)
}
count += 1
return result
}
return i
}
func evaluateToCurrent<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
var precedingLimit: Int? = nil
switch frame.from {
case .preceding(let expr):
let t = try evaluator.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = t.numeric else {
throw QueryPlanError.nonConstantExpression
}
precedingLimit = Int(n.value)
default:
break
}
var group = group
if case .unbound = frame.from {
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard let r = group.next() else { return nil }
self.add(r)
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
return result
}
return i
} else if case .current = frame.from {
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard let r = group.next() else { return nil }
self.add(r)
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
self.remove(r)
return result
}
return i
} else {
var buffer = [SPARQLResultSolution<Term>]()
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard let r = group.next() else { return nil }
if let l = precedingLimit, !buffer.isEmpty, buffer.count > l {
let r = buffer.first!
self.remove(r)
buffer.removeFirst()
}
buffer.append(r)
self.add(r)
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
return result
}
return i
}
}
func evaluateFromCurrent<I: IteratorProtocol>(_ group: I, frame: WindowFrame, variableName: String, evaluator: ExpressionEvaluator) throws -> AnyIterator<SPARQLResultSolution<Term>> where I.Element == SPARQLResultSolution<Term> {
var followingLimit: Int? = nil
switch frame.to {
case .following(let expr):
let t = try evaluator.evaluate(expression: expr, result: SPARQLResultSolution<Term>(bindings: [:]))
guard let n = t.numeric else {
throw QueryPlanError.nonConstantExpression
}
followingLimit = Int(n.value)
default:
break
}
var group = group
if case .unbound = frame.to {
var buffer = Array(consuming: &group)
buffer.forEach { self.add($0) }
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard !buffer.isEmpty else { return nil }
let r = buffer.removeFirst()
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
self.remove(r)
return result
}
return i
} else if case .current = frame.to {
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard let r = group.next() else { return nil }
self.add(r)
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
self.remove(r)
return result
}
return i
} else {
var buffer : [SPARQLResultSolution<Term>]
if let limit = followingLimit {
buffer = Array(consuming: &group, limit: limit+1)
} else {
buffer = Array(consuming: &group)
}
buffer.forEach { self.add($0) }
let i = AnyIterator { () -> SPARQLResultSolution<Term>? in
guard !buffer.isEmpty else { return nil }
let r = buffer.removeFirst()
var result = r
if let v = self.value() {
result = result.extended(variable: variableName, value: v) ?? result
}
self.remove(r)
if let r = group.next() {
buffer.append(r)
self.add(r)
}
return result
}
return i
}
}
}
private func windowAggregation(_ agg: Aggregation) -> SlidingWindowImplementation {
let ee = evaluator
switch agg {
case .countAll:
var value = 0
return SlidingWindowImplementation(
add: { (_) in value += 1 },
remove: { (_) in value -= 1 },
value: { return Term(integer: value) }
)
case let .count(expr, _):
var value = 0
return SlidingWindowImplementation(
add: { (r) in
if let _ = try? ee.evaluate(expression: expr, result: r) {
value += 1
}
},
remove: { (r) in
if let _ = try? ee.evaluate(expression: expr, result: r) {
value -= 1
}
},
value: { return Term(integer: value) }
)
case let .sum(expr, _):
var intCount = 0
var fltCount = 0
var decCount = 0
var dblCount = 0
var int = NumericValue.integer(0)
var flt = NumericValue.float(mantissa: 0, exponent: 0)
var dec = NumericValue.decimal(Decimal(integerLiteral: 0))
var dbl = NumericValue.double(mantissa: 0, exponent: 0)
return SlidingWindowImplementation(
add: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r), let n = t.numeric {
switch n {
case .integer(_):
intCount += 1
int += n
case .float:
fltCount += 1
flt += n
case .decimal:
decCount += 1
dec += n
case .double:
dblCount += 1
dbl += n
}
}
},
remove: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r), let n = t.numeric {
switch n {
case .integer:
intCount -= 1
int -= n
case .float:
fltCount -= 1
flt -= n
case .decimal:
decCount -= 1
dec -= n
case .double:
dblCount -= 1
dbl -= n
}
}
},
value: {
var value = NumericValue.integer(0)
if intCount > 0 { value += int }
if fltCount > 0 { value += flt }
if decCount > 0 { value += dec }
if dblCount > 0 { value += dbl }
return value.term
}
)
case let .avg(expr, _):
var intCount = 0
var fltCount = 0
var decCount = 0
var dblCount = 0
var int = NumericValue.integer(0)
var flt = NumericValue.float(mantissa: 0, exponent: 0)
var dec = NumericValue.decimal(Decimal(integerLiteral: 0))
var dbl = NumericValue.double(mantissa: 0, exponent: 0)
return SlidingWindowImplementation(
add: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r), let n = t.numeric {
switch n {
case .integer:
intCount += 1
int += n
case .float:
fltCount += 1
flt += n
case .decimal:
decCount += 1
dec += n
case .double:
dblCount += 1
dbl += n
}
}
},
remove: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r), let n = t.numeric {
switch n {
case .integer:
intCount -= 1
int -= n
case .float:
fltCount -= 1
flt -= n
case .decimal:
decCount -= 1
dec -= n
case .double:
dblCount -= 1
dbl -= n
}
}
},
value: {
var value = NumericValue.integer(0)
if intCount > 0 { value += int }
if fltCount > 0 { value += flt }
if decCount > 0 { value += dec }
if dblCount > 0 { value += dbl }
let count = NumericValue.integer(intCount + fltCount + decCount + dblCount)
return (value / count).term
}
)
case .min(let expr):
var values = [Term]()
return SlidingWindowImplementation(
add: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r) {
values.append(t)
}
},
remove: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r) {
if let i = values.firstIndex(of: t) {
precondition(i == 0)
values.remove(at: i)
}
}
},
value: { return values.min() }
)
case .max(let expr):
var values = [Term]()
return SlidingWindowImplementation(
add: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r) {
values.append(t)
}
},
remove: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r) {
if let i = values.firstIndex(of: t) {
precondition(i == 0)
values.remove(at: i)
}
}
},
value: { return values.max() }
)
case .sample(let expr):
var value : Term? = nil
return SlidingWindowImplementation(
add: { (r) in
if let t = try? ee.evaluate(expression: expr, result: r) {
value = t
}
},
remove: { (_) in return },
value: { return value }
)
case let .groupConcat(expr, sep, _):
var values = [Term?]()
return SlidingWindowImplementation(
add: { (r) in
let t = try? ee.evaluate(expression: expr, result: r)
values.append(t)
},
remove: { (_) in
values.remove(at: 0)
},
value: {
let strings = values.compactMap { $0?.value }
let j = strings.joined(separator: sep)
return Term(string: j)
}
)
}
}
}
public struct HeapSortLimitPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var comparators: [Algebra.SortComparator]
var limit: Int
var evaluator: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Heap Sort with Limit \(limit) { \(comparators) }" }
fileprivate struct SortElem {
var result: SPARQLResultSolution<Term>
var terms: [Term?]
}
private var sortFunction: (SortElem, SortElem) -> Bool {
let cmps = self.comparators
return { (a, b) -> Bool in
let pairs = zip(a.terms, b.terms)
for (cmp, pair) in zip(cmps, pairs) {
guard let lhs = pair.0 else { return true }
guard let rhs = pair.1 else { return false }
if lhs == rhs {
continue
}
var sorted = lhs > rhs
if !cmp.ascending {
sorted = !sorted
}
return sorted
}
return false
}
}
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try child.evaluate(metrics)
var heap = Heap(sort: sortFunction)
for r in i {
let terms = comparators.map { (cmp) in
try? evaluator.evaluate(expression: cmp.expression, result: r)
}
let elem = SortElem(result: r, terms: terms)
heap.insert(elem)
if heap.count > limit {
heap.remove()
}
}
let rows = heap.sort().map { $0.result }.prefix(limit)
return AnyIterator(rows.makeIterator())
}
}
public struct ExistsPlan: UnaryQueryPlan, QueryPlanSerialization {
public var child: QueryPlan
var pattern: QueryPlan
var variable: String
var patternAlgebra: Algebra
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String {
let s = SPARQLSerializer(prettyPrint: true)
do {
let q = try Query(form: .select(.star), algebra: patternAlgebra)
let tokens = try q.sparqlTokens()
let query = s.serialize(tokens)
return "Exists ?\(variable) ← { \(query.filter { $0 != "\n" }) }"
} catch {
return "*** Failed to serialize EXISTS algebra into SPARQL string ***"
}
}
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
let i = try child.evaluate(metrics)
let pattern = self.pattern
let variable = self.variable
let s = i.lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
metrics.resumeEvaluation(token: metricsToken)
defer { metrics.endEvaluation(metricsToken) }
let columns = r.keys.map { Node.variable($0, binding: true) }
let row = r.keys.map { r[$0] }
let table = TablePlan(columns: columns, rows: [row], metricsToken: metricsToken)
let plan = NestedLoopJoinPlan(lhs: table, rhs: pattern, metricsToken: metricsToken)
guard let existsIter = try? plan.evaluate(metrics) else {
return nil
}
if let _ = existsIter.next() {
return r.extended(variable: variable, value: Term.trueValue)
} else {
return r.extended(variable: variable, value: Term.falseValue)
}
}
return AnyIterator(s.makeIterator())
}
}
/********************************************************************************************************/
// -
/********************************************************************************************************/
public protocol PathPlan: PlanSerializable {
var selfDescription: String { get }
var children : [PathPlan] { get }
func evaluate(from: Node, to: Node, in: Node) throws -> AnyIterator<SPARQLResultSolution<Term>>
}
public struct PathQueryPlan: NullaryQueryPlan, QueryPlanSerialization {
public var subject: Node
public var path: PathPlan
public var object: Node
public var graph: Node
public var metricsToken: QueryPlanEvaluationMetrics.Token
public var selfDescription: String { return "Path { \(subject) ---> \(object) in graph \(graph) }" }
public var properties: [PlanSerializable] { return [path] }
public var isJoinIdentity: Bool { return false }
public var isUnionIdentity: Bool { return false }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
return try path.evaluate(from: subject, to: object, in: graph)
}
}
public extension PathPlan {
var arity: Int { return children.count }
var selfDescription: String {
return "\(self)"
}
func serialize(depth: Int=0) -> String {
let indent = String(repeating: " ", count: (depth*2))
let name = self.selfDescription
var d = "\(indent)\(name)\n"
for c in self.children {
d += c.serialize(depth: depth+1)
}
return d
}
internal func alp(term: Term, path: PathPlan, graph: Term) throws -> AnyIterator<Term> {
var v = Set<Term>()
try alp(term: term, path: path, seen: &v, graph: graph)
return AnyIterator(v.makeIterator())
}
internal func alp(term: Term, path: PathPlan, seen: inout Set<Term>, graph: Term) throws {
guard !seen.contains(term) else { return }
seen.insert(term)
let node : Node = .variable(".pp", binding: true)
for r in try path.evaluate(from: .bound(term), to: node, in: .bound(graph)) {
if let term = r[node] {
try alp(term: term, path: path, seen: &seen, graph: graph)
}
}
}
}
public struct NPSPathPlan: PathPlan {
public var iris: [Term]
var store: QuadStoreProtocol
public var children: [PathPlan] { return [] }
public var selfDescription: String { return "NPS { \(iris) }" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
switch (subject, object) {
case let (.bound(_), .variable(oname, binding: bind)):
let objectGraphPairs = try evaluate(from: subject, in: graph)
if bind {
let i = objectGraphPairs.lazy.map { (o, g) -> SPARQLResultSolution<Term> in
var bindings : [String: Term] = [oname: o]
if case .variable(let v, _) = graph {
bindings[v] = g
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(i.makeIterator())
} else {
let i = objectGraphPairs.lazy.map { (_, g) -> SPARQLResultSolution<Term> in
var bindings : [String: Term] = [:]
if case .variable(let v, _) = graph {
bindings[v] = g
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(i.makeIterator())
}
case (.bound(_), .bound(let o)):
let objectGraphPairs = try evaluate(from: subject, in: graph)
let i = objectGraphPairs.lazy.compactMap { (term, g) -> SPARQLResultSolution<Term>? in
guard term == o else { return nil }
var bindings : [String: Term] = [:]
if case .variable(let v, _) = graph {
bindings[v] = g
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(i.makeIterator())
case (.variable(let s, _), .bound(_)):
let p : Node = .variable(".p", binding: true)
let qp = QuadPattern(subject: subject, predicate: p, object: object, graph: graph)
let i = try store.quads(matching: qp)
let set = Set(iris)
return AnyIterator {
repeat {
guard let q = i.next() else { return nil }
let p = q.predicate
guard !set.contains(p) else { continue }
var bindings : [String: Term] = [s: q.subject]
if case .variable(let v, _) = graph {
bindings[v] = q.graph
}
return SPARQLResultSolution<Term>(bindings: bindings)
} while true
}
case let (.variable(s, _), .variable(o, _)):
let p : Node = .variable(".p", binding: true)
let qp = QuadPattern(subject: subject, predicate: p, object: object, graph: graph)
let i = try store.quads(matching: qp)
let set = Set(iris)
return AnyIterator {
repeat {
guard let q = i.next() else { return nil }
let p = q.predicate
guard !set.contains(p) else { continue }
var bindings : [String: Term] = [s: q.subject, o: q.object]
if case .variable(let v, _) = graph {
bindings[v] = q.graph
}
return SPARQLResultSolution<Term>(bindings: bindings)
} while true
}
}
}
public func evaluate(from subject: Node, in graph: Node) throws -> AnyIterator<(Term, Term)> {
let object = Node.variable(".npso", binding: true)
let predicate = Node.variable(".npsp", binding: true)
let quad = QuadPattern(subject: subject, predicate: predicate, object: object, graph: graph)
let i = try store.quads(matching: quad)
// OPTIMIZE: this can be made more efficient by adding an NPS function to the store,
// and allowing it to do the filtering based on a SPARQLResultSolution<UInt64> objects before
// materializing the terms
let set = Set(iris)
return AnyIterator {
repeat {
guard let q = i.next() else { return nil }
let p = q.predicate
guard !set.contains(p) else { continue }
return (q.object, q.graph)
} while true
}
}
}
public struct LinkPathPlan : PathPlan {
public var predicate: Term
var store: QuadStoreProtocol
public var children: [PathPlan] { return [] }
public var selfDescription: String { return "Link { \(predicate) }" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
// print("eval(linkPath[\(subject) \(predicate) \(object) \(graph)])")
let qp = QuadPattern(subject: subject, predicate: .bound(predicate), object: object, graph: graph)
let r = try store.results(matching: qp)
return r
}
// public func evaluate(from subject: Node, in graph: Node) throws -> AnyIterator<Term> {
// let object = Node.variable(".lpo", binding: true)
// let qp = QuadPattern(
// subject: subject,
// predicate: .bound(predicate),
// object: object,
// graph: graph
// )
//// print("eval(linkPath[from: \(qp)])")
// let plan = QuadPlan(quad: qp, store: store)
// let i = try plan.evaluate().lazy.compactMap {
// return $0[object]
// }
// return AnyIterator(i.makeIterator())
// }
}
public struct UnionPathPlan: PathPlan {
public var lhs: PathPlan
public var rhs: PathPlan
public var children: [PathPlan] { return [lhs, rhs] }
public var selfDescription: String { return "Alt" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
let l = try lhs.evaluate(from: subject, to: object, in: graph)
let r = try rhs.evaluate(from: subject, to: object, in: graph)
return AnyIterator(ConcatenatingIterator(l, r))
}
}
public struct SequencePathPlan: PathPlan {
public var lhs: PathPlan
public var joinNode: Node
public var rhs: PathPlan
public var children: [PathPlan] { return [lhs, rhs] }
public var selfDescription: String { return "Seq { \(joinNode) }" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
// print("eval(sequencePath[\(subject) --> \(object)])")
guard case .variable(_, _) = joinNode else {
print("*** invalid child in query plan evaluation")
throw QueryPlanError.invalidChild
}
let l = try lhs.evaluate(from: subject, to: joinNode, in: graph)
var results = [SPARQLResultSolution<Term>]()
for lr in l {
if let j = lr[joinNode] {
let r = try rhs.evaluate(from: .bound(j), to: object, in: graph)
for rr in r {
var result = rr
if case .variable(let v, _) = graph {
// ensure we join on the graph variable
guard let lg = lr[v], let rg = rr[v], lg == rg else { continue }
}
if case .variable(let name, true) = subject, let term = lr[subject] {
result = result.extended(variable: name, value: term) ?? result
}
results.append(result)
}
}
}
return AnyIterator(results.makeIterator())
}
}
public struct InversePathPlan: PathPlan {
public var child: PathPlan
public var children: [PathPlan] { return [child] }
public var selfDescription: String { return "Inv" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
return try child.evaluate(from: object, to: subject, in: graph)
}
}
public struct PlusPathPlan : PathPlan {
public var child: PathPlan
var store: QuadStoreProtocol
public var children: [PathPlan] { return [child] }
public var selfDescription: String { return "Plus" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
let graphs: [Term]
if case .bound(let g) = graph {
graphs = [g]
} else {
graphs = Array(store.graphs())
}
var branches = try graphs.compactMap { (graph) -> AnyIterator<SPARQLResultSolution<Term>>? in
switch subject {
case .bound:
var v = Set<Term>()
let frontierNode : Node = .variable(".pp-plus", binding: true)
for r in try child.evaluate(from: subject, to: frontierNode, in: .bound(graph)) {
if let n = r[frontierNode] {
// print("First step of + resulted in term: \(n)")
try alp(term: n, path: child, seen: &v, graph: graph)
}
}
// print("ALP resulted in: \(v)")
let i = v.lazy.map { (term) -> SPARQLResultSolution<Term> in
if case .variable(let name, true) = object {
return SPARQLResultSolution<Term>(bindings: [name: term])
} else {
return SPARQLResultSolution<Term>(bindings: [:])
}
}
return AnyIterator(i.makeIterator())
case .variable(let s, binding: _):
switch object {
case .variable:
var iterators = [AnyIterator<SPARQLResultSolution<Term>>]()
for gn in store.graphTerms(in: graph) {
let results = try evaluate(from: .bound(gn), to: object, in: .bound(graph)).lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
r.extended(variable: s, value: gn)
}
iterators.append(AnyIterator(results.makeIterator()))
}
return AnyIterator { () -> SPARQLResultSolution<Term>? in
repeat {
guard let i = iterators.first else { return nil }
if let r = i.next() {
return r
} else {
iterators.removeFirst(1)
}
} while true
}
case .bound:
// ?subject path+ <bound>
let ipath = PlusPathPlan(child: InversePathPlan(child: child), store: store)
return try ipath.evaluate(from: object, to: subject, in: .bound(graph))
}
}
}
var current = branches.popLast()
return AnyIterator {
while true {
if let current = current {
if let element = current.next() {
return element
}
}
guard !branches.isEmpty else { return nil }
current = branches.popLast()
}
}
}
}
public struct StarPathPlan : PathPlan {
public var child: PathPlan
var store: QuadStoreProtocol
public var children: [PathPlan] { return [child] }
public var selfDescription: String { return "Star" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
let graphs: [Term]
if case .bound(let g) = graph {
graphs = [g]
} else {
graphs = Array(store.graphs())
}
var branches = try graphs.compactMap { (graphTerm) -> AnyIterator<SPARQLResultSolution<Term>>? in
switch subject {
case .bound(let term):
var v = Set<Term>()
try alp(term: term, path: child, seen: &v, graph: graphTerm)
// print("ALP resulted in: \(v)")
switch object {
case let .variable(name, binding: true):
let i = v.lazy.map { (term) -> SPARQLResultSolution<Term> in
var bindings = [name: term]
if case .variable(let v, _) = graph {
bindings[v] = graphTerm
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(i.makeIterator())
case .variable(_, binding: false):
let i = v.lazy.map { (term) -> SPARQLResultSolution<Term> in
var bindings = [String: Term]()
if case .variable(let v, _) = graph {
bindings[v] = graphTerm
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(i.makeIterator())
case .bound(let o):
let i = v.lazy.compactMap { (term) -> SPARQLResultSolution<Term>? in
guard term == o else { return nil }
var bindings = [String:Term]()
if case .variable(let v, _) = graph {
bindings[v] = graphTerm
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(i.prefix(1).makeIterator())
}
case .variable(let s, binding: _):
switch object {
case .variable:
var iterators = [AnyIterator<SPARQLResultSolution<Term>>]()
for gn in store.graphTerms(in: graphTerm) {
let results = try evaluate(from: .bound(gn), to: object, in: .bound(graphTerm)).lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
let rr = r.extended(variable: s, value: gn)
if case .variable(let v, _) = graph {
if let rr = rr {
return rr.extended(variable: v, value: graphTerm)
} else {
return nil
}
} else {
return rr
}
}
iterators.append(AnyIterator(results.makeIterator()))
}
return AnyIterator { () -> SPARQLResultSolution<Term>? in
repeat {
guard let i = iterators.first else { return nil }
if let r = i.next() {
if case .variable(let v, _) = graph {
return r.extended(variable: v, value: graphTerm)
} else {
return r
}
} else {
iterators.removeFirst(1)
}
} while true
}
case .bound:
let ipath = StarPathPlan(child: InversePathPlan(child: child), store: store)
let i = try ipath.evaluate(from: object, to: subject, in: .bound(graphTerm))
let j = i.lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
if case .variable(let v, _) = graph {
return r.extended(variable: v, value: graphTerm)
} else {
return r
}
}
return AnyIterator(j.makeIterator())
}
}
}
var current = branches.popLast()
return AnyIterator {
while true {
if let current = current {
if let element = current.next() {
return element
}
}
guard !branches.isEmpty else { return nil }
current = branches.popLast()
}
}
}
}
public struct ZeroOrOnePathPlan : PathPlan {
public var child: PathPlan
var store: QuadStoreProtocol
public var children: [PathPlan] { return [child] }
public var selfDescription: String { return "ZeroOrOne" }
public func evaluate(from subject: Node, to object: Node, in graph: Node) throws -> AnyIterator<SPARQLResultSolution<Term>> {
let graphs: [Term]
if case .bound(let g) = graph {
graphs = [g]
} else {
graphs = Array(store.graphs())
}
var branches = try graphs.compactMap { (graphTerm) -> AnyIterator<SPARQLResultSolution<Term>>? in
let i = try child.evaluate(from: subject, to: object, in: .bound(graphTerm))
switch (subject, object) {
case (.variable(let s, _), .variable):
let gn = store.graphTerms(in: graphTerm)
let results = try gn.lazy.map { (term) -> AnyIterator<SPARQLResultSolution<Term>> in
let i = try child.evaluate(from: .bound(term), to: object, in: .bound(graphTerm))
let j = i.lazy.map { (r) -> SPARQLResultSolution<Term> in
var bindings = r.bindings
bindings[s] = term
if case .variable(let v, _) = graph {
bindings[v] = graphTerm
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(j.makeIterator())
}
return AnyIterator(results.joined().makeIterator())
case (.bound, .bound):
if subject == object {
var bindings = [String: Term]()
if case .variable(let v, _) = graph {
bindings[v] = graphTerm
}
let r = [SPARQLResultSolution<Term>(bindings: bindings)]
return AnyIterator(r.makeIterator())
} else {
return i
}
case let (.bound(term), .variable(name, _)), let (.variable(name, _), .bound(term)):
let r = [SPARQLResultSolution<Term>(bindings: [name: term])]
var seen = Set<Term>()
let j = i.lazy.compactMap { (r) -> SPARQLResultSolution<Term>? in
guard let t = r[name] else { return nil }
guard t != term else { return nil }
guard !seen.contains(t) else { return nil }
seen.insert(t)
var bindings = r.bindings
if case .variable(let v, _) = graph {
bindings[v] = graphTerm
}
return SPARQLResultSolution<Term>(bindings: bindings)
}
return AnyIterator(ConcatenatingIterator(r.makeIterator(), j.makeIterator()))
}
}
var current = branches.popLast()
return AnyIterator {
while true {
if let current = current {
if let element = current.next() {
return element
}
}
guard !branches.isEmpty else { return nil }
current = branches.popLast()
}
}
}
}
/********************************************************************************************************/
protocol Aggregate {
func handle(_ row: SPARQLResultSolution<Term>)
func result() -> Term?
}
public struct AggregationPlan: UnaryQueryPlan, QueryPlanSerialization {
private class CountAllAggregate: Aggregate {
var count: Int
init() {
self.count = 0
}
func handle(_ row: SPARQLResultSolution<Term>) {
count += 1
}
func result() -> Term? {
return Term(integer: count)
}
}
private class MinimumAggregate: Aggregate {
var value: Term?
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.expression = expression
self.value = nil
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
let term = try? ee.evaluate(expression: expression, result: row)
if let t = value {
if let term = term, term < t {
value = term
}
} else {
value = term
}
}
func result() -> Term? {
return value
}
}
private class MaximumAggregate: Aggregate {
var value: Term?
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.expression = expression
self.value = nil
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
let term = try? ee.evaluate(expression: expression, result: row)
if let t = value {
if let term = term, term > t {
value = term
}
} else {
value = term
}
}
func result() -> Term? {
return value
}
}
private class AverageAggregate: Aggregate {
var error: Bool
var value: NumericValue
var count: Int
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.error = false
self.expression = expression
self.value = .integer(0)
self.count = 0
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
if let n = term.numeric {
value = value + n
count += 1
} else {
error = true
}
}
}
func result() -> Term? {
guard !error else { return nil }
let avg = value / .integer(count)
return avg.term
}
}
private class AverageDistinctAggregate: Aggregate {
var error: Bool
var values: Set<NumericValue>
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.error = false
self.expression = expression
self.values = Set()
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
if let n = term.numeric {
values.insert(n)
} else {
error = true
}
}
}
func result() -> Term? {
guard !error else { return nil }
let value = values.reduce(NumericValue.integer(0)) { $0 + $1 }
let avg = value / .integer(values.count)
return avg.term
}
}
private class SumAggregate: Aggregate {
var error: Bool
var value: NumericValue
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.error = false
self.expression = expression
self.value = .integer(0)
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
if let n = term.numeric {
value = value + n
} else {
error = true
}
}
}
func result() -> Term? {
guard !error else { return nil }
return value.term
}
}
private class SumDistinctAggregate: Aggregate {
var error: Bool
var values: Set<NumericValue>
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.error = false
self.expression = expression
self.values = Set()
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
if let n = term.numeric {
values.insert(n)
} else {
error = true
}
}
}
func result() -> Term? {
guard !error else { return nil }
let value = values.reduce(NumericValue.integer(0)) { $0 + $1 }
return value.term
}
}
private class CountAggregate: Aggregate {
var count: Int
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.expression = expression
self.count = 0
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let _ = try? ee.evaluate(expression: expression, result: row) {
count += 1
}
}
func result() -> Term? {
return Term(integer: count)
}
}
private class CountDistinctAggregate: Aggregate {
var values: Set<Term>
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.expression = expression
self.values = Set()
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
values.insert(term)
}
}
func result() -> Term? {
return Term(integer: values.count)
}
}
private class SampleAggregate: Aggregate {
var value: Term?
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, evaluator: ExpressionEvaluator) {
self.expression = expression
self.value = nil
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
value = term
}
}
func result() -> Term? {
return value
}
}
private class GroupConcatDistinctAggregate: Aggregate {
var values: Set<Term>
var separator: String
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, separator: String, evaluator: ExpressionEvaluator) {
self.expression = expression
self.separator = separator
self.values = Set()
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
values.insert(term)
}
}
func result() -> Term? {
let s = values.sorted().map { $0.value }.joined(separator: separator)
return Term(string: s)
}
}
private class GroupConcatAggregate: Aggregate {
var value: String
var separator: String
var expression: Expression
var ee: ExpressionEvaluator
init(expression: Expression, separator: String, evaluator: ExpressionEvaluator) {
self.expression = expression
self.separator = separator
self.value = ""
self.ee = evaluator
}
func handle(_ row: SPARQLResultSolution<Term>) {
if let term = try? ee.evaluate(expression: expression, result: row) {
if !value.isEmpty {
value += separator
}
value += term.value
}
}
func result() -> Term? {
return Term(string: value)
}
}
public var child: QueryPlan
var groups: [Expression]
var emitOnEmpty: Bool
var aggregates: [String: () -> (Aggregate)]
var ee: ExpressionEvaluator
public var metricsToken: QueryPlanEvaluationMetrics.Token
public init(child: QueryPlan, groups: [Expression], aggregates: Set<Algebra.AggregationMapping>, metricsToken: QueryPlanEvaluationMetrics.Token) {
self.child = child
self.groups = groups
self.aggregates = [:]
let ee = ExpressionEvaluator(base: nil)
self.ee = ee
self.emitOnEmpty = self.groups.isEmpty
self.metricsToken = metricsToken
for a in aggregates {
switch a.aggregation {
case .countAll:
self.aggregates[a.variableName] = { return CountAllAggregate() }
case let .count(e, true):
self.aggregates[a.variableName] = { return CountDistinctAggregate(expression: e, evaluator: ee) }
case let .count(e, false):
self.aggregates[a.variableName] = { return CountAggregate(expression: e, evaluator: ee) }
case .min(let e):
self.aggregates[a.variableName] = { return MinimumAggregate(expression: e, evaluator: ee) }
case .max(let e):
self.aggregates[a.variableName] = { return MaximumAggregate(expression: e, evaluator: ee) }
case .sample(let e):
self.aggregates[a.variableName] = { return SampleAggregate(expression: e, evaluator: ee) }
case let .groupConcat(e, sep, true):
self.aggregates[a.variableName] = { return GroupConcatDistinctAggregate(expression: e, separator: sep, evaluator: ee) }
case let .groupConcat(e, sep, false):
self.aggregates[a.variableName] = { return GroupConcatAggregate(expression: e, separator: sep, evaluator: ee) }
case let .avg(e, false):
self.aggregates[a.variableName] = { return AverageAggregate(expression: e, evaluator: ee) }
case let .avg(e, true):
self.aggregates[a.variableName] = { return AverageDistinctAggregate(expression: e, evaluator: ee) }
case let .sum(e, true):
self.aggregates[a.variableName] = { return SumDistinctAggregate(expression: e, evaluator: ee) }
case let .sum(e, false):
self.aggregates[a.variableName] = { return SumAggregate(expression: e, evaluator: ee) }
}
}
}
public var selfDescription: String { return "Aggregate \(aggregates) over groups \(groups)" }
public func evaluate(_ metrics: QueryPlanEvaluationMetrics) throws -> AnyIterator<SPARQLResultSolution<Term>> {
metrics.startEvaluation(metricsToken, self)
defer { metrics.endEvaluation(metricsToken) }
var aggData = [[Term?]:[String:Aggregate]]()
var seenRows = 0
for r in try child.evaluate(metrics) {
seenRows += 1
let group = groups.map { try? ee.evaluate(expression: $0, result: r) }
if let _ = aggData[group] {
} else {
// instantiate all aggregates for this group
aggData[group] = Dictionary(uniqueKeysWithValues: aggregates.map { ($0.key, $0.value()) })
}
aggData[group]!.forEach { (_, agg) in
agg.handle(r)
}
}
guard aggData.count > 0 else {
if emitOnEmpty {
let d = aggregates.compactMap { (name, a) -> (String, Term)? in
let agg = a()
guard let term = agg.result() else { return nil }
return (name, term)
}
let r = SPARQLResultSolution<Term>(bindings: Dictionary(uniqueKeysWithValues: d))
return AnyIterator([r].makeIterator())
} else {
return AnyIterator([].makeIterator())
}
}
let rows = aggData.compactMap { (group, aggs) -> SPARQLResultSolution<Term>? in
var groupTerms = [String:Term]()
for (e, t) in zip(groups, group) {
if case .node(.variable(let name, _)) = e {
if let term = t {
groupTerms[name] = term
}
}
}
let d = Dictionary(uniqueKeysWithValues: aggs.compactMap { (a) -> (String, Term)? in
guard let term = a.value.result() else {
return nil
}
return (a.key, term)
})
let result = groupTerms.merging(d) { (l, r) in l }
return SPARQLResultSolution<Term>(bindings: result)
}
return AnyIterator(rows.makeIterator())
}
}
|
1631645d01a4b3f548ae1fe4bcd79a36
| 40.036342 | 308 | 0.518836 | false | false | false | false |
WalterCreazyBear/Swifter30
|
refs/heads/master
|
PhoneHistory/PhoneHistory/AboutMeViewController.swift
|
mit
|
1
|
//
// AboutMeViewController.swift
// PhoneHistory
//
// Created by 熊伟 on 2017/6/18.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class AboutMeViewController: UIViewController {
var test:Int = 12
lazy var scrollView:UIScrollView = {
let scrollView = UIScrollView.init(frame: CGRect.zero)
scrollView.backgroundColor = UIColor.white
return scrollView
}()
lazy var headerImageView:UIImageView = {
let headerImageView = UIImageView(frame:CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: 125))
headerImageView.image = UIImage.init(named: "header-contact")
return headerImageView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
self.scrollView.frame = self.view.bounds
self.view.addSubview(self.scrollView)
self.headerImageView.frame = CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: 125)
self.scrollView.addSubview(self.headerImageView)
}
}
|
1e451dc2f79c1d55240155c5d8c55999
| 30.555556 | 116 | 0.669014 | false | false | false | false |
BrooksWon/ios-charts
|
refs/heads/master
|
Charts/Classes/Renderers/CandleStickChartRenderer.swift
|
apache-2.0
|
33
|
//
// CandleStickChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol CandleStickChartRendererDelegate
{
func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData!
func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter!
func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Double
func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int
}
public class CandleStickChartRenderer: LineScatterCandleRadarChartRenderer
{
public weak var delegate: CandleStickChartRendererDelegate?
public init(delegate: CandleStickChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(#context: CGContext)
{
var candleData = delegate!.candleStickChartRendererCandleData(self)
for set in candleData.dataSets as! [CandleChartDataSet]
{
if (set.isVisible)
{
drawDataSet(context: context, dataSet: set)
}
}
}
private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint())
private var _bodyRect = CGRect()
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawDataSet(#context: CGContext, dataSet: CandleChartDataSet)
{
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var phaseX = _animator.phaseX
var phaseY = _animator.phaseY
var bodySpace = dataSet.bodySpace
var entries = dataSet.yVals as! [CandleChartDataEntry]
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
CGContextSaveGState(context)
CGContextSetLineWidth(context, dataSet.shadowWidth)
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++)
{
// get the entry
var e = entries[j]
if (e.xIndex < _minX || e.xIndex > _maxX)
{
continue
}
// calculate the shadow
_shadowPoints[0].x = CGFloat(e.xIndex)
_shadowPoints[0].y = CGFloat(e.high) * phaseY
_shadowPoints[1].x = CGFloat(e.xIndex)
_shadowPoints[1].y = CGFloat(e.low) * phaseY
trans.pointValuesToPixel(&_shadowPoints)
// draw the shadow
var shadowColor: UIColor! = nil
if (dataSet.shadowColorSameAsCandle)
{
if (e.open > e.close)
{
shadowColor = dataSet.decreasingColor ?? dataSet.colorAt(j)
}
else if (e.open < e.close)
{
shadowColor = dataSet.increasingColor ?? dataSet.colorAt(j)
}
}
if (shadowColor === nil)
{
shadowColor = dataSet.shadowColor ?? dataSet.colorAt(j);
}
CGContextSetStrokeColorWithColor(context, shadowColor.CGColor)
CGContextStrokeLineSegments(context, _shadowPoints, 2)
// calculate the body
_bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace
_bodyRect.origin.y = CGFloat(e.close) * phaseY
_bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x
_bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y
trans.rectValueToPixel(&_bodyRect)
// draw body differently for increasing and decreasing entry
if (e.open > e.close)
{
var color = dataSet.decreasingColor ?? dataSet.colorAt(j)
if (dataSet.isDecreasingFilled)
{
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, _bodyRect)
}
else
{
CGContextSetStrokeColorWithColor(context, color.CGColor)
CGContextStrokeRect(context, _bodyRect)
}
}
else if (e.open < e.close)
{
var color = dataSet.increasingColor ?? dataSet.colorAt(j)
if (dataSet.isIncreasingFilled)
{
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, _bodyRect)
}
else
{
CGContextSetStrokeColorWithColor(context, color.CGColor)
CGContextStrokeRect(context, _bodyRect)
}
}
else
{
CGContextSetStrokeColorWithColor(context, shadowColor.CGColor)
CGContextStrokeRect(context, _bodyRect)
}
}
CGContextRestoreGState(context)
}
public override func drawValues(#context: CGContext)
{
var candleData = delegate!.candleStickChartRendererCandleData(self)
if (candleData === nil)
{
return
}
var defaultValueFormatter = delegate!.candleStickChartDefaultRendererValueFormatter(self)
// if values are drawn
if (candleData.yValCount < Int(ceil(CGFloat(delegate!.candleStickChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)))
{
var dataSets = candleData.dataSets
for (var i = 0; i < dataSets.count; i++)
{
var dataSet = dataSets[i]
if (!dataSet.isDrawValuesEnabled)
{
continue
}
var valueFont = dataSet.valueFont
var valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var entries = dataSet.yVals as! [CandleChartDataEntry]
var entryFrom = dataSet.entryForXIndex(_minX)
var entryTo = dataSet.entryForXIndex(_maxX)
var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0)
var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count)
var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY)
var lineHeight = valueFont.lineHeight
var yOffset: CGFloat = lineHeight + 5.0
for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * _animator.phaseX + CGFloat(minx))); j < count; j++)
{
var x = positions[j].x
var y = positions[j].y
if (!viewPortHandler.isInBoundsRight(x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y))
{
continue
}
var val = entries[j].high
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
}
public override func drawExtras(#context: CGContext)
{
}
private var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint())
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var candleData = delegate!.candleStickChartRendererCandleData(self)
if (candleData === nil)
{
return
}
for (var i = 0; i < indices.count; i++)
{
var xIndex = indices[i].xIndex; // get the x-position
var set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
var e = set.entryForXIndex(xIndex) as! CandleChartDataEntry!
if (e === nil || e.xIndex != xIndex)
{
continue
}
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: set.axisDependency)
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
CGContextSetLineWidth(context, set.highlightLineWidth)
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var low = CGFloat(e.low) * _animator.phaseY
var high = CGFloat(e.high) * _animator.phaseY
var y = (low + high) / 2.0
_highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(delegate!.candleStickChartRendererChartYMax(self)))
_highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(delegate!.candleStickChartRendererChartYMin(self)))
_highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMin(self)), y: y)
_highlightPtsBuffer[3] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: y)
trans.pointValuesToPixel(&_highlightPtsBuffer)
// draw the lines
drawHighlightLines(context: context, points: _highlightPtsBuffer,
horizontal: set.isHorizontalHighlightIndicatorEnabled, vertical: set.isVerticalHighlightIndicatorEnabled)
}
}
}
|
7004b8a8fad74df1dbf3dc23fef2edfc
| 37.865574 | 246 | 0.560364 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne
|
refs/heads/master
|
表格拆分/表格拆分/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// 表格拆分
//
// Created by bingoogol on 14/10/2.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/**
1.在UITableViewController中,如果要实例化视图,直接实例化self.tableView即可
2.乳沟要使用默认的平板表格UITableViewStylePlain,可以不用重写loadView方法
*/
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
let CELL_ID = "MyCell"
let EMBEDVIEW_HEIGHT:CGFloat = 200
let ROW_HEIGHT:CGFloat = 92
var tableView:UITableView!
var embedView:UIView!
// 动画的表格行
var animationRows:NSMutableArray!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame, style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = ROW_HEIGHT
tableView.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(tableView)
embedView = UIView(frame: CGRectMake(0, 0, tableView.bounds.width, EMBEDVIEW_HEIGHT))
embedView.backgroundColor = UIColor.orangeColor()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 15
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as MyCell!
if cell == nil {
cell = MyCell(style: UITableViewCellStyle.Default, reuseIdentifier: CELL_ID)
cell.contentView.backgroundColor = UIColor.whiteColor()
cell.selectionStyle = UITableViewCellSelectionStyle.None
}
cell.textLabel?.text = "cell-\(indexPath.row)"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// 选中某一个表格行后,将下方的表格行向下方移动SUBVIEW_HEIGHT的高度
// 未打开,做打开操作
if animationRows == nil {
// 新建一个数组,把所有可能有动画的表格行的indexPath全部记录下来,一遍之后还原
animationRows = NSMutableArray(array: tableView.indexPathsForVisibleRows()!)
// 表格的偏移。注意:表格是继承自UIScrollView,有偏移量
var bottomY = tableView.contentOffset.y + tableView.frame.height
// 计算准备插入子视图的y值
var selectedCell = tableView.cellForRowAtIndexPath(indexPath)!
var subViewY = selectedCell.frame.origin.y + ROW_HEIGHT
// 准备加入子视图的最大y值
var maxSubViewY = bottomY - EMBEDVIEW_HEIGHT
// 判断空间是否够大
if maxSubViewY >= subViewY {
embedView.frame.origin.y = subViewY
// 空间够大。只要挪动选中行下方的表格行即可
UIView.animateWithDuration(0.5, animations: {
for path in self.animationRows {
var cell:MyCell = tableView.cellForRowAtIndexPath(path as NSIndexPath) as MyCell!
var frame = cell.frame
// 记录初始y位置
cell.originY = frame.origin.y
if path.row > indexPath.row {
frame.origin.y += self.EMBEDVIEW_HEIGHT
cell.frame = frame
}
}
})
} else {
embedView.frame.origin.y = maxSubViewY
// 空间不够。上面的要挪,下边也要挪
UIView.animateWithDuration(0.5, animations: {
var delta = subViewY - maxSubViewY
for path in self.animationRows {
var cell:MyCell = tableView.cellForRowAtIndexPath(path as NSIndexPath) as MyCell!
var frame = cell.frame
// 记录初始y位置
cell.originY = frame.origin.y
if path.row > indexPath.row {
frame.origin.y += (self.EMBEDVIEW_HEIGHT - delta)
} else {
frame.origin.y -= delta
}
cell.frame = frame
}
})
}
tableView.insertSubview(embedView, atIndex: 0)
} else {
// 已打开,做复位操作
UIView.animateWithDuration(0.5, animations: {
for path in self.animationRows {
var cell:MyCell = tableView.cellForRowAtIndexPath(path as NSIndexPath) as MyCell!
var frame = cell.frame
frame.origin.y = cell.originY
cell.frame = frame
}
}, completion: { (finished:Bool) in
self.embedView.removeFromSuperview()
self.animationRows = nil
}
)
}
}
}
|
746fe9369b69ec61703f35932c11d377
| 37.888889 | 109 | 0.550725 | false | false | false | false |
krad/buffie
|
refs/heads/master
|
Sources/Buffie/Capture/Camera/Camera.swift
|
mit
|
1
|
import Foundation
import AVKit
/// Enum representing the position of the camera
public enum CameraPosition {
case front
case back
fileprivate var osPosition: AVCaptureDevice.Position {
switch self {
case .front: return AVCaptureDevice.Position.front
case .back: return AVCaptureDevice.Position.back
}
}
}
/// Enum representing things that can go wrong with the camera
///
/// - noCameraFound: Thrown when we can't find a device suitable for capturing video
public enum CaptureDeviceError: Error {
case deviceNotFound(deviceID: String)
case noDeviceAvailable(type: AVMediaType)
case noDevicesAvailable
}
/// Protocol used to handle changes to the camera's state
public protocol CameraControlDelegate {
func cameraStarted()
func cameraStopped()
func cameraInteruppted()
}
public protocol CaptureDevice {
func start()
func stop()
}
public class Camera {
/// Which camera to use front/back
public var position: CameraPosition?
/// Used to handle control events with the camera. Like when it starts, stops, or is interuppted
public var controlDelegate: CameraControlDelegate?
/// Used to obtain and classified samples streamed from the camera (audio or video samples)
internal var cameraReader: AVReaderProtocol
/// The actual camera session object. Used for stubbing
internal var cameraSession: CaptureSessionProtocol?
public init(_ position: CameraPosition = .back,
reader: AVReaderProtocol = AVReader(),
controlDelegate: CameraControlDelegate? = nil) throws {
self.position = position
self.controlDelegate = controlDelegate
self.cameraReader = reader
self.cameraSession = try CaptureSession(position.osPosition,
controlDelegate: self,
cameraReader: self.cameraReader)
}
public init(videoDeviceID: String,
audioDeviceID: String,
reader: AVReaderProtocol = AVReader(),
controlDelegate: CameraControlDelegate? = nil) throws {
self.controlDelegate = controlDelegate
self.cameraReader = reader
self.cameraSession = try CaptureSession(videoDeviceID: videoDeviceID,
audioDeviceID: audioDeviceID,
controlDelegate: self,
cameraReader: self.cameraReader)
}
public init(videoDeviceID: String?,
audioDeviceID: String?,
reader: AVReaderProtocol = AVReader(),
controlDelegate: CameraControlDelegate? = nil) throws {
self.controlDelegate = controlDelegate
self.cameraReader = reader
self.cameraSession = try CaptureSession(videoDeviceID: videoDeviceID,
audioDeviceID: audioDeviceID,
controlDelegate: self,
cameraReader: self.cameraReader)
}
/// Start the camera
public func start() {
self.cameraSession?.start()
}
public func start(onComplete: ((AVCaptureSession) -> Void)? = nil) {
self.cameraSession?.start(onComplete: onComplete)
}
/// Stop the camera
public func stop() {
self.cameraSession?.stop()
}
/// Attempt to flip the camera
public func flip() {
guard let session = cameraSession else { return }
if self.position == .front {
if session.changeToCamera(position: .back) {
self.position = .back
}
} else {
if session.changeToCamera(position: .front) {
self.position = .front
}
}
}
}
extension Camera: CaptureDevice { }
extension Camera: CameraControlDelegate {
public func cameraStarted() {
self.controlDelegate?.cameraStarted()
}
public func cameraStopped() {
self.controlDelegate?.cameraStopped()
}
public func cameraInteruppted() {
self.controlDelegate?.cameraInteruppted()
}
}
|
17a886809cea2c4b775f30b0f354f4ad
| 30.817518 | 101 | 0.594402 | false | false | false | false |
JackEsad/Eureka
|
refs/heads/master
|
Eureka.playground/Contents.swift
|
mit
|
2
|
//: **Eureka Playground** - let us walk you through Eureka! cool features, we will show how to
//: easily create powerful forms using Eureka!
//: It allows us to create complex dynamic table view forms and obviously simple static table view. It's ideal for data entry task or settings pages.
import UIKit
import XCPlayground
import PlaygroundSupport
//: Start by importing Eureka module
import Eureka
//: Any **Eureka** form must extend from `FromViewController`
let formController = FormViewController()
PlaygroundPage.current.liveView = formController.view
let b = [Int]()
b.last
let f = Form()
f.last
//: ## Operators
//: ### +++
//: Adds a Section to a Form when the left operator is a Form
let form = Form() +++ Section()
//: When both operators are a Section it creates a new Form containing both Section and return the created form.
let form2 = Section("First") +++ Section("Second") +++ Section("Third")
//: Notice that you don't need to add parenthesis in the above expresion, +++ operator is left associative so it will create a form containing the 2 first sections and then append last Section (Third) to the created form.
//: form and form2 don't have any row and are not useful at all. Let's add some rows.
//: ### +++
//: Can be used to append a row to a form without having to create a Section to contain the row. The form section is implicitly created as a result of the +++ operator.
formController.form +++ TextRow("Text")
//: it can also be used to append a Section like this:
formController.form +++ Section()
//: ### <<<
//: Can be used to append rows to a section.
formController.form.last! <<< SwitchRow("Switch") { $0.title = "Switch"; $0.value = true }
//: it can also be used to create a section and append rows to it. Let's use that to add a new section to the form
formController.form +++ PhoneRow("Phone") { $0.title = "Phone"}
<<< IntRow("IntRow") { $0.title = "Int"; $0.value = 5 }
formController.view
//: # Callbacks
//: Rows might have several closures associated to be called at different events. Let's see them one by one. Sadly, we can not interact with it in our playground.
//: ### onChange callback
//: Will be called when the value of a row changes. Lots of things can be done with this feature. Let's create a new section for the new rows:
formController.form +++ Section("Callbacks") <<< SwitchRow("scr1") { $0.title = "Switch to turn red"; $0.value = false }
.onChange({ row in
if row.value == true {
row.cell.backgroundColor = .red
} else {
row.cell.backgroundColor = .black
}
})
//: Now when we change the value of this row its background color will change to red. Try that by (un)commenting the following line:
formController.view
formController.form.last?.last?.baseValue = true
formController.view
//: Notice that we set the `baseValue` attribute because we did not downcast the result of `formController.form.last?.last`. It is essentially the same as the `value` attribute
//: ### cellSetup and cellUpdate callbacks
//: The cellSetup will be called when the cell of this row is configured (just once at the beginning)
//: and the cellUpdate will be called when it is updated (each time it reappears on screen). Here you should define the appearance of the cell
formController.form.last! <<< SegmentedRow<String>("Segments") { $0.title = "Choose an animal"; $0.value = "🐼"; $0.options = ["🐼", "🐶", "🐻"]}.cellSetup({ cell, _ in
cell.backgroundColor = .red
}).cellUpdate({ (cell, _) -> Void in
cell.textLabel?.textColor = .yellow
})
//: ### onSelection and onPresent callbacks
//: OnSelection will be called when this row is selected (tapped by the user). It might be useful for certain rows instead of the onChange callback.
//: OnPresent will be called when a row that presents another view controller is tapped. It might be useful to set up the presented view controller.
//: We can not try them out in the playground but they can be set just like the others.
formController.form.last! <<< SegmentedRow<String>("Segments2") { $0.title = "Choose an animal"; $0.value = "🐼"; $0.options = ["🐼", "🐶", "🐻"]
}.onCellSelection { cell, row in
print("\(cell) for \(row) got selected")
}
formController.view
//: ### Hiding rows
//: We can hide rows by defining conditions that will tell if they should appear on screen or not. Let's create a row that will hide when the previous one is "🐼".
formController.form.last! <<< LabelRow("Confirm") {
$0.title = "Are you sure you do not want the 🐼?"
$0.hidden = "$Segments2 == '🐼'"
}
//: Now let's see how this works:
formController.view
formController.form.rowBy(tag: "Segments2")?.baseValue = "🐶"
formController.view
//: We can do the same using functions. Functions are specially useful for more complicated conditions.
//: This applies when the value of the row we depend on is not compatible with NSPredicates (which is not the current case, but anyway).
formController.form.last! <<< LabelRow("Confirm2") {
$0.title = "Well chosen!!"
$0.hidden = Condition.function(["Segments2"]) { form in
if let r: SegmentedRow<String> = form.rowBy(tag: "Segments2") {
return r.value != "🐼"
}
return true
}
}
//: Now let's see how this works:
formController.view
formController.form.rowBy(tag: "Segments2")?.baseValue = "🐼"
formController.view
|
d2b3b1bfbcde1bc7c0c57adaaaaa287b
| 43.975 | 221 | 0.696313 | false | false | false | false |
tylow/surftranslate
|
refs/heads/master
|
surftranslate/SURF_Translate/DeckTableViewController.swift
|
agpl-3.0
|
1
|
//
// DeckTableViewController.swift
// SURF_Translate
//
// Created by Legeng Liu on 6/1/16.
// Copyright © 2016 SURF. All rights reserved.
//
import UIKit
class DeckTableViewController: UITableViewController, UINavigationControllerDelegate{
//MARK: Properties:
//keeps array of Deck objects
var decks = [Deck]()
//favoriteDecks is used *internally* to keep track of all my favorite decks. For sorting purposes etc.
// every time a Deck is favorited, add it to the favoriteDecks array, but also have it in the normal decks array, because the tableview controller displays the decks array. favoriteDecks is not displayed and only used to keep track internally.
var favoriteDecks = [Deck]()
//implementing search. "nil" means no new view controller needed when searching
let searchController = UISearchController(searchResultsController: nil)
var filteredDecks = [Deck]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem()
//making sample Cards and Decks to test stuff
var sampleCards = [Card]()
var sampleCards2 = [Card]()
var sampleCards3 = [Card]()
let card1 = Card(firstPhrase: "1", secondPhrase: "2", numTimesUsed: 0)!
let card2 = Card(firstPhrase: "english", secondPhrase: "arabic", numTimesUsed : 0)!
let card3 = Card(firstPhrase: "I need water", secondPhrase: "أحتاج إلى الماء", numTimesUsed :0)!
let card4 = Card(firstPhrase: "Hello", secondPhrase: "Salaam", numTimesUsed: 0)!
sampleCards += [card1, card2, card3, card4]
sampleCards2 += [card1, card3, card4]
sampleCards3 += [card3, card4]
let deck1 = Deck(name: "Refugee", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: true)!
let deck2 = Deck(name: "UNHCR Phrasebook", cards: sampleCards2, language1: "English", language2: "Arabic", isFavorite: true)!
let deck3 = Deck(name: "UNHCR Phrasebook Extended extended extended extended extended dddddddddddddddddddddddddddddddd", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck4 = Deck(name: "Doctors to Refugees", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck5 = Deck(name: "Commonly used in camp", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck6 = Deck(name: "Customized deck", cards: sampleCards, language1: "English", language2: "Arabic", isFavorite: false)!
let deck7 = Deck(name: "Imported Online", cards: sampleCards3, language1: "English", language2: "Arabic", isFavorite: false)!
decks += [deck1, deck2, deck3, deck4, deck5, deck6, deck7]
//filtering favorited decks from all decks
favoriteDecks = decks.filter{$0.isFavorite == true}
//MARK: search
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = true //maybe we should set this to true?
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
func filterContentForSearchText(searchText: String){
filteredDecks = decks.filter{deck in
return deck.name.lowercaseString.containsString(searchText.lowercaseString)
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//when searching, return the # of Decks that fit search criteria, otherwise return total #
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.active && searchController.searchBar.text != "" {
return filteredDecks.count
} else {
return decks.count
}
}
//lets DeckTableViewController set the values inside each cell to decks that are already filtered
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "DeckTableViewCell" //this unique identifier can be edited in Attributes section of Cell object
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! DeckTableViewCell
var deck: Deck
if searchController.active && searchController.searchBar.text != "" {
deck = filteredDecks[indexPath.row]
} else {
deck = decks[indexPath.row]
}
cell.deckName.text = deck.name
cell.numberOfCards.text = "Cards:" + String(deck.cards.count)
cell.deckFavoriteControl.isFavorite = deck.isFavorite
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// 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?) {
var selectedDeck: Deck
if segue.identifier == "showCards"{
let showCardsViewController = segue.destinationViewController as! CardTableViewController
if let selectedDeckCell = sender as? DeckTableViewCell{
let indexPath = tableView.indexPathForCell(selectedDeckCell)!
if searchController.active && searchController.searchBar.text != "" {
selectedDeck = filteredDecks[indexPath.row]
} else {
selectedDeck = decks[indexPath.row]
}
showCardsViewController.cards = selectedDeck.cards
showCardsViewController.navigationItem.title? = selectedDeck.name
}
} else if segue.identifier == "AddDeck"{
print ("add new deck")
}
}
@IBAction func unwindToDeckList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? NewDeckViewController, newDeck = sourceViewController.newDeck {
// if new made Deck is favorited, then this code below puts it on top, below the other Favorited decks.
if newDeck.isFavorite == true{
let newIndexPath = NSIndexPath(forRow: favoriteDecks.count, inSection: 0)
decks.insert(newDeck, atIndex: favoriteDecks.count)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
favoriteDecks.append(newDeck)
// if not a Favorite, then put on bottom of all the decks
} else {
let newIndexPath = NSIndexPath(forRow: decks.count, inSection: 0)
decks.append(newDeck)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
}
}
}
extension DeckTableViewController: UISearchResultsUpdating{
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
}
|
a435034951884ac5126fc4b1cbfc4ae3
| 41.022727 | 248 | 0.659924 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/SwiftUI/PokeMaster/PokeMaster/View/AppState.swift
|
mit
|
1
|
//
// AppState.swift
// PokeMaster
//
// Created by 黄伯驹 on 2022/1/23.
//
import SwiftUI
struct AppState {
var settings = Settings()
}
extension AppState {
struct Settings {
var loginUser: User?
enum AccountBehavior: CaseIterable {
case register, login
}
var accountBehavior = AccountBehavior.login
var email = ""
var password = ""
var verifyPassword = ""
enum Sorting: CaseIterable {
case id, name, color, favorite
}
var showEnglishName = true
var sorting = Sorting.id
var showFavoriteOnly = false
}
}
extension AppState {
}
|
04794dca2f059dd246be8626a540d5c9
| 15.681818 | 51 | 0.527248 | false | false | false | false |
devincoughlin/swift
|
refs/heads/master
|
test/SourceKit/CodeComplete/complete_group_overloads.swift
|
apache-2.0
|
5
|
// XFAIL: broken_std_regex
struct A {}
struct B {}
func aaa() {}
func aaa(_ x: A) {}
func aaa(_ x: B) {}
func aaa(_ x: B, y: B) {}
func aaa(x x: B, y: B) {}
func aab() {}
func test001() {
#^TOP_LEVEL_0,aa^#
}
// RUN: %complete-test -group=overloads -tok=TOP_LEVEL_0 %s | %FileCheck -check-prefix=TOP_LEVEL_0 %s
// TOP_LEVEL_0-LABEL: aaa:
// TOP_LEVEL_0-NEXT: aaa()
// TOP_LEVEL_0-NEXT: aaa(x: A)
// TOP_LEVEL_0-NEXT: aaa(x: B)
// TOP_LEVEL_0-NEXT: aaa(x: B, y: B)
// TOP_LEVEL_0-NEXT: aaa(x: B, y: B)
// TOP_LEVEL_0-NEXT: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float)
// TOP_LEVEL_0-NEXT: #imageLiteral(resourceName: String)
// TOP_LEVEL_0-NEXT: aab()
struct Foo {
func aaa() {}
func aaa(_ x: A) {}
func aaa(_ x: B) {}
func aaa(_ x: B, y: B) {}
func aaa(x x: B, y: B) {}
func aab() {}
}
func test002() {
Foo().#^FOO_INSTANCE_0^#
}
// RUN: %complete-test -group=overloads -tok=FOO_INSTANCE_0 %s | %FileCheck -check-prefix=FOO_INSTANCE_0 %s
// FOO_INSTANCE_0-LABEL: aaa:
// FOO_INSTANCE_0-NEXT: aaa()
// FOO_INSTANCE_0-NEXT: aaa(x: A)
// FOO_INSTANCE_0-NEXT: aaa(x: B)
// FOO_INSTANCE_0-NEXT: aaa(x: B, y: B)
// FOO_INSTANCE_0-NEXT: aaa(x: B, y: B)
// FOO_INSTANCE_0-NEXT: aab()
extension Foo {
static func bbb() {}
static func bbb(_ x: A) {}
static func bbc() {}
}
func test003() {
Foo.#^FOO_QUAL_0^#
}
// RUN: %complete-test -group=overloads -tok=FOO_QUAL_0 %s | %FileCheck -check-prefix=FOO_QUAL_0 %s
// FOO_QUAL_0-LABEL: bbb:
// FOO_QUAL_0-NEXT: bbb()
// FOO_QUAL_0-NEXT: bbb(x: A)
// FOO_QUAL_0-NEXT: bbc()
extension Foo {
subscript(x: A) -> A { return A() }
subscript(x: B) -> B { return B() }
}
func test004() {
Foo()#^FOO_SUBSCRIPT_0^#
}
// RUN: %complete-test -group=overloads -tok=FOO_SUBSCRIPT_0 %s | %FileCheck -check-prefix=FOO_SUBSCRIPT_0 %s
// FOO_SUBSCRIPT_0-LABEL: [:
// FOO_SUBSCRIPT_0-NEXT: [x: A]
// FOO_SUBSCRIPT_0-NEXT: [x: B]
struct Bar {
init() {}
init(x: A) {}
init(x: B) {}
}
func test005() {
Bar#^BAR_INIT_0^#
}
// Inline a lonely group
// RUN: %complete-test -group=overloads -add-inner-results -no-inner-operators -tok=BAR_INIT_0 %s | %FileCheck -check-prefix=BAR_INIT_0 %s
// BAR_INIT_0-LABEL: (:
// BAR_INIT_0: ()
// BAR_INIT_0-NEXT: (x: A)
// BAR_INIT_0-NEXT: (x: B)
// BAR_INIT_0-NEXT: .self
extension Bar {
func foo()
}
func test006() {
Bar#^BAR_INIT_1^#
}
// RUN: %complete-test -group=overloads -add-inner-results -no-inner-operators -tok=BAR_INIT_1 %s | %FileCheck -check-prefix=BAR_INIT_1 %s
// BAR_INIT_1-LABEL: (:
// BAR_INIT_1-NEXT: ()
// BAR_INIT_1-NEXT: (x: A)
// BAR_INIT_1-NEXT: (x: B)
// BAR_INIT_1-NEXT: foo(self: Bar)
func test007() {
#^BAR_INIT_2^#
// RUN: %complete-test -add-inits-to-top-level -group=overloads -tok=BAR_INIT_2 %s | %FileCheck -check-prefix=BAR_INIT_2 %s
// BAR_INIT_2-LABEL: Bar:
// BAR_INIT_2-NEXT: Bar
// BAR_INIT_2-NEXT: Bar()
// BAR_INIT_2-NEXT: Bar(x: A)
// BAR_INIT_2-NEXT: Bar(x: B)
|
4def8cdf8bbadb0d8c7b547b1c6b2a9a
| 24.895652 | 138 | 0.598388 | false | true | false | false |
SergeMaslyakov/audio-player
|
refs/heads/master
|
app/src/controllers/audio-source/AudioSourcesViewController.swift
|
apache-2.0
|
1
|
//
// AudioSourcesViewController.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 07/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import UIKit
import Reusable
import SwiftyBeaver
import TableKit
import Dip
import DipUI
class AudioSourcesViewController: UIViewController, StoryboardSceneBased, Loggable {
static let sceneStoryboard = UIStoryboard(name: StoryboardScenes.source.rawValue, bundle: nil)
var audioSourceService: AudioSourceDataService?
var tableDirector: TableDirector!
var refreshControl: UIRefreshControl!
@IBOutlet weak var stubDataView: StubDataView! {
didSet {
stubDataView.retryDelegate = self
}
}
@IBOutlet weak var tableView: UITableView! {
didSet {
tableDirector = TableDirector(tableView: tableView)
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
if #available(iOS 10.0, *) {
tableView.refreshControl = refreshControl
} else {
tableView.addSubview(refreshControl)
}
tableView.alpha = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "SOURCE_TITLE".localized(withFile: .source)
installTable()
refresh(manual: false)
}
func installTable() {
let section = TableSection()
section.headerHeight = ThemeHeightHelper.AudioSource.sectionHeaderHeight
section.footerHeight = ThemeHeightHelper.AudioSource.sectionFooterHeight
tableDirector += section
}
func refresh(manual: Bool) {
if manual {
stubDataView?.dataLoading()
}
DispatchQueue.main.async {
self.loadData()
}
}
}
//
// MARK: Populate table with data
//
extension AudioSourcesViewController {
func loadData() {
let audioSources = audioSourceService?.loadSources()
guard let sources = audioSources else {
// TODO - added logging - fatal error
return
}
tableDirector.sections[0].clear()
let section = tableDirector.sections[0]
for source in sources {
let row = TableRow<AudioSourceTableViewCell>(item: source)
.on(.click) { options in
self.tableDirector.tableView?.deselectRow(at: options.indexPath, animated: true)
}
section += row
}
tableDirector.reload()
refreshControl.endRefreshing()
stubDataView.dataWasLoaded()
}
}
//
// MARK: Retry delegate
//
extension AudioSourcesViewController: StubDataRetryProtocol {
func userRequestRetry(from stubView:StubDataView) {
refresh(manual: true)
}
}
|
5816bab25764569a5fbebf9170df5406
| 23.775862 | 104 | 0.629088 | false | false | false | false |
nkirby/Humber
|
refs/heads/master
|
_lib/HMGithub/_src/API/GithubAPI.swift
|
mit
|
1
|
// =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import Janus
import Alamofire
import ReactiveCocoa
import HMCore
// =======================================================
public enum GithubAPIError: ErrorType {
case NotLoggedIn
case RequestError
case InvalidResponse
case Unknown
}
public class GithubAPI: NSObject {
private let manager = Alamofire.Manager()
private let userID: String
private let token: GithubOAuthToken
public init?(context: ServiceContext) {
let query = GithubKeychainStoreQuery()
guard context.userIdentifier != "anon",
let dict = KeychainStore().keychainItem(query: query),
let token = GithubOAuthToken(keychainItem: dict) else {
return nil
}
self.userID = context.userIdentifier
self.token = token
super.init()
self.setupManager()
}
private func setupManager() {
}
// =======================================================
// MARK: - Generation
private func request(method method: Alamofire.Method, endpoint: String, parameters: [String: AnyObject]?) -> SignalProducer<Alamofire.Request, GithubAPIError> {
return SignalProducer { observer, disposable in
if Config.routerLogging {
print("\(method): \(endpoint)")
}
let headers = [
"Accept": "application/vnd.github.v3+json",
"Authorization": "token \(self.token.accessToken)"
]
let url = "https://api.github.com" + endpoint
let request = Alamofire.Manager.sharedInstance.request(method, url, parameters: parameters, encoding: ParameterEncoding.URL, headers: headers)
observer.sendNext(request)
observer.sendCompleted()
}
}
private func enqueue(request request: Alamofire.Request) -> SignalProducer<AnyObject, GithubAPIError> {
return SignalProducer { observer, disposable in
request.responseJSON { response in
switch response.result {
case .Success(let value):
observer.sendNext(value)
observer.sendCompleted()
return
default:
break
}
observer.sendFailed(.RequestError)
}
disposable.addDisposable {
request.cancel()
}
}
}
private func parse<T: JSONDecodable>(response response: AnyObject, toType type: T.Type) -> SignalProducer<T, GithubAPIError> {
return SignalProducer { observer, disposable in
if let dict = response as? JSONDictionary, let obj = JSONParser.model(type).from(dict) {
observer.sendNext(obj)
observer.sendCompleted()
} else {
observer.sendFailed(.InvalidResponse)
}
}
}
private func parseFeed<T: JSONDecodable>(response response: AnyObject, toType type: T.Type) -> SignalProducer<[T], GithubAPIError> {
return SignalProducer { observer, disposable in
if let arr = response as? JSONArray, let feed = JSONParser.models(type).from(arr) {
observer.sendNext(feed)
observer.sendCompleted()
} else {
observer.sendFailed(.InvalidResponse)
}
}
}
// =======================================================
// MARK: - Request Performing
public func enqueueOnly(request request: GithubRequest) -> SignalProducer<AnyObject, GithubAPIError> {
return self.request(method: request.method, endpoint: request.endpoint, parameters: request.parameters)
.flatMap(.Latest) { self.enqueue(request: $0) }
}
public func enqueueAndParse<T: JSONDecodable>(request request: GithubRequest, toType type: T.Type) -> SignalProducer<T, GithubAPIError> {
return self.request(method: request.method, endpoint: request.endpoint, parameters: request.parameters)
.flatMap(.Latest) { self.enqueue(request: $0) }
.flatMap(.Latest) { self.parse(response: $0, toType: type) }
}
public func enqueueAndParseFeed<T: JSONDecodable>(request request: GithubRequest, toType type: T.Type) -> SignalProducer<[T], GithubAPIError> {
return self.request(method: request.method, endpoint: request.endpoint, parameters: request.parameters)
.flatMap(.Latest) { self.enqueue(request: $0) }
.flatMap(.Latest) { self.parseFeed(response: $0, toType: type) }
}
}
|
6b14ca63ed5573a99d6eca1a8458cc6a
| 35.886364 | 164 | 0.561101 | false | false | false | false |
wowiwj/WDayDayCook
|
refs/heads/master
|
WDayDayCook/WDayDayCook/Views/Cell/Choose/MyCollectionCell.swift
|
mit
|
1
|
//
// MyCollectionCellTableViewCell.swift
// WDayDayCook
//
// Created by wangju on 16/7/26.
// Copyright © 2016年 wangju. All rights reserved.
//
import UIKit
import SnapKit
import RealmSwift
enum CellStyle:Int {
case newFood
case recipeList
case themeList
case recipeDiscussList
var cellTitle :(title:String,image:UIImage){
switch self {
case .newFood:
return ("每日新菜馆",UIImage(named: "icon- 每日新品~iphone")!)
case .recipeList:
return ("当红人气菜",UIImage(named: "icon-热门推荐~iphone")!)
case .themeList:
return ("美食全攻略",UIImage(named: "icon-主题~iphone")!)
case .recipeDiscussList:
return ("话题推荐",UIImage(named: "icon-话题~iphone")!)
}
}
}
protocol MyCollectionCellDelegete {
func didSeclectItem(_ item:Object)
}
class MyCollectionCell: BaseTitleViewCell {
var delegate: MyCollectionCellDelegete?
// MARK: - 接收的参数
var newFoodItems: Results<NewFood>?{
didSet{
cellStyle = CellStyle.newFood
}
}
/// 热门推荐
var recipeList: Results<FoodRecmmand>? {
didSet{
cellStyle = CellStyle.recipeList
}
}
var cellStyle:CellStyle?{
didSet{
titleView.title = cellStyle?.cellTitle.title
titleView.image = cellStyle?.cellTitle.image
collectionView.reloadData()
}
}
let ArticleCellID = "ArticleCell"
// MARK: - 布局设置
// 每日新品和热门推荐以及话题推荐的layout
lazy var flowLayout:UICollectionViewFlowLayout = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
return flowLayout
}()
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.flowLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
return collectionView
}()
override func layoutSubviews() {
super.layoutSubviews()
let height = self.collectionView.frame.size.height
let size = CGSize(width: WDConfig.articleCellWidth.autoAdjust(), height: height)
flowLayout.itemSize = size
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(collectionView)
collectionView.register(UINib(nibName: ArticleCellID, bundle: nil), forCellWithReuseIdentifier: ArticleCellID)
collectionView.snp.makeConstraints { (make) in
make.top.equalTo(titleView.snp.bottom)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension MyCollectionCell: UICollectionViewDataSource,UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let cellStyle = cellStyle else
{
return 0
}
switch cellStyle {
case .newFood:
return newFoodItems?.count ?? 0
case .recipeList:
return recipeList?.count ?? 0
default:
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ArticleCellID, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cellStyle = cellStyle else
{
return
}
switch cellStyle {
case .newFood:
let articleCell = cell as! ArticleCell
articleCell.newFood = newFoodItems![(indexPath as NSIndexPath).item]
case .recipeList:
let articleCell = cell as! ArticleCell
articleCell.recipe = recipeList![(indexPath as NSIndexPath).item]
default:
break
}
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print((indexPath as NSIndexPath).item)
guard let delegate = delegate else
{
return
}
if let recipeList = recipeList
{
delegate.didSeclectItem(recipeList[(indexPath as NSIndexPath).row])
print()
return
}
if let newFoodItems = newFoodItems {
delegate.didSeclectItem(newFoodItems[(indexPath as NSIndexPath).row])
// print(newFoodItems[indexPath.row])
return
}
}
}
|
206a8b1100effacd9279c7b6a9525370
| 25.032258 | 138 | 0.605417 | false | false | false | false |
silence0201/Swift-Study
|
refs/heads/master
|
AdvancedSwift/字符串/Code Unit Views.playgroundpage/Contents.swift
|
mit
|
1
|
/*:
## Code Unit Views
Sometimes it's necessary to drop down to a lower level of abstraction and
operate directly on Unicode code units instead of characters. There are a few
common reasons for this.
Firstly, maybe you actually need the code units, perhaps for rendering into a
UTF-8-encoded webpage, or for interoperating with a non-Swift API that takes
them.
For an example of an API that requires code units, let's look at using
`CharacterSet` from the Foundation framework in combination with Swift strings.
The `CharacterSet` API is mostly defined in terms of Unicode scalars. So if you
wanted to use `CharacterSet` to split up a string, you could do it via the
`unicodeScalars` view:
*/
//#-hidden-code
import Foundation
//#-end-hidden-code
//#-editable-code
extension String {
func words(with charset: CharacterSet = .alphanumerics) -> [String] {
return self.unicodeScalars.split {
!charset.contains($0)
}.map(String.init)
}
}
let s = "Wow! This contains _all_ kinds of things like 123 and \"quotes\"?"
s.words()
//#-end-editable-code
/*:
This will break the string apart at every non-alphanumeric character, giving you
an array of `String.UnicodeScalarView` slices. They can be turned back into
strings via `map` with the `String` initializer that takes a
`UnicodeScalarView`.
The good news is, even after going through this fairly extensive pipeline, the
string slices in `words` will *still* just be views onto the original string;
this property isn't lost by going via the `UnicodeScalarView` and back again.
A second reason for using these views is that operating on code units rather
than fully composed characters can be much faster. This is because to compose
grapheme clusters, you must look ahead of every character to see if it's
followed by combining characters. To see just how much faster these views can
be, take a look at the performance section later on.
Finally, the UTF-16 view has one benefit the other views don't have: it can be
random access. This is possible for just this view type because, as we've seen,
this is how strings are held internally within the `String` type. What this
means is the *n*^th^ UTF-16 code unit is always at the *n*^th^ position in the
buffer (even if the string is in "ASCII buffer mode" – it's just a question of
the width of the entries to advance over).
The Swift team made the decision *not* to conform `String.UTF16View` to
`RandomAccessCollection` in the standard library, though. Instead, they moved
the conformance into Foundation, so you need to import Foundation to take
advantage of it. A comment [in the Foundation source
code](https://github.com/apple/swift/blob/master/stdlib/public/SDK/Foundation/ExtraStringAPIs.swift)
explains why:
``` swift-example
// Random access for String.UTF16View, only when Foundation is
// imported. Making this API dependent on Foundation decouples the
// Swift core from a UTF16 representation.
...
extension String.UTF16View : RandomAccessCollection {}
```
Nothing would break if a future `String` implementation used a different
internal representation. Existing code that relied on the random-access
conformance could take advantage of the option for a `String` to be backed by an
`NSString`, like we discussed above. `NSString` also uses UTF-16 internally.
That said, it's probably rarer than you think to need random access. Most
practical string use cases just need serial access. But some processing
algorithms rely on random access for efficiency. For example, the Boyer-Moore
search algorithm relies on the ability to skip along the text in jumps of
multiple characters.
So you could use the UTF-16 view with algorithms that require such a
characteristic. Another example is the search algorithm we define in the
generics chapter:
*/
//#-hidden-code
import Foundation
extension Collection
where Iterator.Element: Equatable,
SubSequence.Iterator.Element == Iterator.Element,
Indices.Iterator.Element == Index
{
func search<Other: Sequence>(for pattern: Other) -> Index?
where Other.Iterator.Element == Iterator.Element
{
return indices.first { idx in
suffix(from: idx).starts(with: pattern)
}
}
}
//#-end-hidden-code
//#-editable-code
let helloWorld = "Hello, world!"
if let idx = helloWorld.utf16.search(for: "world".utf16)?
.samePosition(in: helloWorld)
{
print(helloWorld[idx..<helloWorld.endIndex])
}
//#-end-editable-code
/*:
But beware\! These convenience or efficiency benefits come at a price, which is
that your code may no longer be completely Unicode-correct. So unfortunately,
the following search will fail:
*/
//#-editable-code
let text = "Look up your Pok\u{0065}\u{0301}mon in a Pokédex."
text.utf16.search(for: "Pokémon".utf16)
//#-end-editable-code
/*:
Unicode defines diacritics that are used to combine with alphabetic characters
as being alphanumeric, so this fares a little better:
*/
//#-editable-code
let nonAlphas = CharacterSet.alphanumerics.inverted
text.unicodeScalars.split(whereSeparator: nonAlphas.contains).map(String.init)
//#-end-editable-code
|
fffd29973a1fcf3eece7d877b084d345
| 35.375887 | 100 | 0.757068 | false | false | false | false |
inamiy/Await
|
refs/heads/master
|
Demo/AwaitDemoTests/AwaitDemoTests.swift
|
mit
|
1
|
//
// AwaitDemoTests.swift
// AwaitDemoTests
//
// Created by Yasuhiro Inami on 2014/06/30.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import XCTest
//import PromiseKit
class AwaitDemoTests: XCTestCase {
let request = NSURLRequest(URL: NSURL(string:"https://github.com"))
var response: NSData?
override func setUp()
{
super.setUp()
println("\n\n\n\n\n")
}
override func tearDown()
{
println("\n\n\n\n\n")
super.tearDown()
}
func testAwait()
{
self.response = await { NSURLConnection.sendSynchronousRequest(self.request, returningResponse:nil, error: nil) }
XCTAssertNotNil(self.response, "Should GET html data.")
}
func testAwaitTuple()
{
let result: (value: Int?, error: NSError?)? = await {
usleep(100_000);
return (nil, NSError(domain: "AwaitDemoTest", code: -1, userInfo: nil))
}
XCTAssertNil(result!.value, "Should not return value.")
XCTAssertNotNil(result!.error, "Should return error.")
}
func testAwaitWithUntil()
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
var shouldStop = false
self.response = await(until: shouldStop) {
dispatch_async(queue) {
usleep(100_000)
shouldStop = true
}
return NSData() // dummy
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitWithTimeout()
{
let timeout = 0.2 // 200ms
self.response = await(timeout: timeout) {
usleep(300_000) // 300ms, sleep well to demonstrate timeout error
return NSData() // dummy
}
XCTAssertNil(self.response, "Should time out and return nil.")
self.response = await(timeout: timeout) {
usleep(100_000) // 100ms
return NSData()
}
XCTAssertNotNil(self.response, "Should GET html data within \(timeout) seconds.")
}
// func testAwaitWithPromiseKit()
// {
// let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//// let queue = dispatch_get_main_queue()
//
// let promise = Promise<NSData> { [weak self] (fulfiller, rejecter) in
// dispatch_async(queue) {
// let data = NSURLConnection.sendSynchronousRequest(self!.request, returningResponse:nil, error: nil)
// fulfiller(data)
// }
// }.then(onQueue: queue) { (data: NSData) -> NSData in
// return data
// }
//
//// self.response = await({ promise.value }, until: { !promise.pending })
// self.response = await(promise)
//
// XCTAssertNotNil(self.response, "Should GET html data.")
// }
func testAwaitWithNSOperation()
{
let operation = NSBlockOperation(block: { usleep(100_000); return })
operation.completionBlock = { println("operation finished.") }
self.response = await(until: operation.finished) {
operation.start()
return NSData() // dummy
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitWithNSOperationQueue()
{
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
for i in 0 ..< 3 {
let operation = NSBlockOperation(block: { usleep(100_000); return })
operation.completionBlock = { println("operation[\(i)] finished.") }
operationQueue.addOperation(operation)
}
self.response = await(until: operationQueue.operationCount == 0) {
return NSData() // dummy
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitFinishable()
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
self.response = await { finish in
dispatch_async(queue) {
usleep(100_000)
finish(NSData()) // dummy
}
}
XCTAssertNotNil(self.response, "Should await for data.")
}
func testAwaitFinishableNoReturn()
{
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
await { finish in
dispatch_async(queue) {
usleep(100_000)
self.response = NSData() // dummy
finish()
}
}
XCTAssertNotNil(self.response, "Should await for data.")
}
}
|
f95d402a4b9253a38ed4c7311c9e6eb6
| 28.771605 | 121 | 0.55339 | false | true | false | false |
WataruSuzuki/StarWarsSpoilerBlocker
|
refs/heads/master
|
StarWarsSpoilerBlocker/RootViewController.swift
|
mit
|
1
|
//
// RootViewController.swift
// StarWarsSpoilerBlocker
//
// Created by 鈴木 航 on 2015/11/28.
// Copyright © 2015年 WataruSuzuki. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
if UIDevice.current.userInterfaceIdiom == .pad {
pageViewRect = pageViewRect.insetBy(dx: 40.0, dy: 40.0)
}
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMove(toParentViewController: self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
}
return _modelController!
}
var _modelController: ModelController? = nil
// MARK: - UIPageViewController delegate methods
func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
if (orientation == .portrait) || (orientation == .portraitUpsideDown) || (UIDevice.current.userInterfaceIdiom == .phone) {
// In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers![0]
let viewControllers = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: true, completion: {done in })
self.pageViewController!.isDoubleSided = false
return .min
}
// In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
let currentViewController = self.pageViewController!.viewControllers![0] as! DataViewController
var viewControllers: [UIViewController]
let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController)
if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfter: currentViewController)
viewControllers = [currentViewController, nextViewController!]
} else {
let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBefore: currentViewController)
viewControllers = [previousViewController!, currentViewController]
}
self.pageViewController!.setViewControllers(viewControllers, direction: .forward, animated: true, completion: {done in })
return .mid
}
}
|
2c6a8d942875480732b9fbf33ef28844
| 50.989247 | 333 | 0.730507 | false | false | false | false |
necrowman/CRLAlamofireFuture
|
refs/heads/master
|
Carthage/Checkouts/Event/Tests/Event/EventTests.swift
|
mit
|
111
|
//
// EventTests.swift
// EventTests
//
// Created by Daniel Leping on 22/04/2016.
// Copyright © 2016 Crossroad Labs s.r.o. All rights reserved.
//
import XCTest
@testable import Event
import ExecutionContext
enum TestEventString : EventProtocol {
typealias Payload = String
case event
}
enum TestEventInt : EventProtocol {
typealias Payload = Int
case event
}
enum TestEventComplex : EventProtocol {
typealias Payload = (String, Int)
case event
}
struct TestEventGroup<E : EventProtocol> {
internal let event:E
private init(_ event:E) {
self.event = event
}
static var string:TestEventGroup<TestEventString> {
return TestEventGroup<TestEventString>(.event)
}
static var int:TestEventGroup<TestEventInt> {
return TestEventGroup<TestEventInt>(.event)
}
static var complex:TestEventGroup<TestEventComplex> {
return TestEventGroup<TestEventComplex>(.event)
}
}
class EventEmitterTest : EventEmitterProtocol {
let dispatcher:EventDispatcher = EventDispatcher()
let context: ExecutionContextType = ExecutionContext.current
func on<E : EventProtocol>(groupedEvent: TestEventGroup<E>) -> EventConveyor<E.Payload> {
return self.on(groupedEvent.event)
}
func emit<E : EventProtocol>(groupedEvent: TestEventGroup<E>, payload:E.Payload) {
self.emit(groupedEvent.event, payload: payload)
}
}
class EventTests: XCTestCase {
func testExample() {
let ec = ExecutionContext(kind: .parallel)
let eventEmitter = EventEmitterTest()
let _ = eventEmitter.on(.string).settle(in: ec).react { s in
print("string:", s)
}
let _ = eventEmitter.on(.int).settle(in: global).react { i in
print("int:", i)
}
let _ = eventEmitter.on(.complex).settle(in: immediate).react { (s, i) in
print("complex: string:", s, "int:", i)
}
let off = eventEmitter.on(.int).map({$0 * 2}).react { i in
}
off()
let semitter = eventEmitter.on(.complex).filter { (s, i) in
i % 2 == 0
}.map { (s, i) in
s + String(i*100)
}
let _ = semitter.react { string in
print(string)
}
eventEmitter.emit(.int, payload: 7)
eventEmitter.emit(.string, payload: "something here")
eventEmitter.emit(.complex, payload: ("whoo hoo", 7))
eventEmitter.emit(.complex, payload: ("hey", 8))
eventEmitter.emit(.error, payload: NSError(domain: "", code: 1, userInfo: nil))
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
|
4ae2fd794c55ffe953617cb79e5a04e9
| 25.651376 | 96 | 0.595869 | false | true | false | false |
tkremenek/swift
|
refs/heads/master
|
test/refactoring/ConvertAsync/convert_async_wrapper.swift
|
apache-2.0
|
1
|
// RUN: %empty-directory(%t)
enum CustomError : Error {
case e
}
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 -enable-experimental-concurrency | %FileCheck -check-prefix=FOO1 %s
func foo1(_ completion: @escaping () -> Void) {}
// FOO1: convert_async_wrapper.swift [[# @LINE-1]]:1 -> [[# @LINE-1]]:1
// FOO1-NEXT: @completionHandlerAsync("foo1()", completionHandlerIndex: 0)
// FOO1-EMPTY:
// FOO1-NEXT: convert_async_wrapper.swift [[# @LINE-4]]:49 -> [[# @LINE-4]]:49
// FOO1-EMPTY:
// FOO1-EMPTY:
// FOO1-EMPTY:
// FOO1-NEXT: convert_async_wrapper.swift [[# @LINE-8]]:49 -> [[# @LINE-8]]:49
// FOO1-NEXT: func foo1() async {
// FOO1-NEXT: return await withCheckedContinuation { continuation in
// FOO1-NEXT: foo1() {
// FOO1-NEXT: continuation.resume(returning: ())
// FOO1-NEXT: }
// FOO1-NEXT: }
// FOO1-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 -enable-experimental-concurrency | %FileCheck -check-prefix=FOO2 %s
func foo2(arg: String, _ completion: @escaping (String) -> Void) {}
// FOO2: convert_async_wrapper.swift [[# @LINE-1]]:1 -> [[# @LINE-1]]:1
// FOO2-NEXT: @completionHandlerAsync("foo2(arg:)", completionHandlerIndex: 1)
// FOO2-EMPTY:
// FOO2-NEXT: convert_async_wrapper.swift [[# @LINE-4]]:68 -> [[# @LINE-4]]:68
// FOO2-EMPTY:
// FOO2-EMPTY:
// FOO2-EMPTY:
// FOO2-NEXT: convert_async_wrapper.swift [[# @LINE-8]]:68 -> [[# @LINE-8]]:68
// FOO2: func foo2(arg: String) async -> String {
// FOO2-NEXT: return await withCheckedContinuation { continuation in
// FOO2-NEXT: foo2(arg: arg) { result in
// FOO2-NEXT: continuation.resume(returning: result)
// FOO2-NEXT: }
// FOO2-NEXT: }
// FOO2-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO3 %s
func foo3(arg: String, _ arg2: Int, _ completion: @escaping (String?) -> Void) {}
// FOO3: func foo3(arg: String, _ arg2: Int) async -> String? {
// FOO3-NEXT: return await withCheckedContinuation { continuation in
// FOO3-NEXT: foo3(arg: arg, arg2) { result in
// FOO3-NEXT: continuation.resume(returning: result)
// FOO3-NEXT: }
// FOO3-NEXT: }
// FOO3-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO4 %s
func foo4(_ completion: @escaping (Error?) -> Void) {}
// FOO4: func foo4() async throws {
// FOO4-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO4-NEXT: foo4() { error in
// FOO4-NEXT: if let error = error {
// FOO4-NEXT: continuation.resume(throwing: error)
// FOO4-NEXT: return
// FOO4-NEXT: }
// FOO4-NEXT: continuation.resume(returning: ())
// FOO4-NEXT: }
// FOO4-NEXT: }
// FOO4-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO5 %s
func foo5(_ completion: @escaping (Error) -> Void) {}
// FOO5: func foo5() async -> Error {
// FOO5-NEXT: return await withCheckedContinuation { continuation in
// FOO5-NEXT: foo5() { result in
// FOO5-NEXT: continuation.resume(returning: result)
// FOO5-NEXT: }
// FOO5-NEXT: }
// FOO5-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO6 %s
func foo6(_ completion: @escaping (String?, Error?) -> Void) {}
// FOO6: func foo6() async throws -> String {
// FOO6-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO6-NEXT: foo6() { result, error in
// FOO6-NEXT: if let error = error {
// FOO6-NEXT: continuation.resume(throwing: error)
// FOO6-NEXT: return
// FOO6-NEXT: }
// FOO6-NEXT: guard let result = result else {
// FOO6-NEXT: fatalError("Expected non-nil result 'result' for nil error")
// FOO6-NEXT: }
// FOO6-NEXT: continuation.resume(returning: result)
// FOO6-NEXT: }
// FOO6-NEXT: }
// FOO6-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO7 %s
func foo7(_ completion: @escaping (String?, Int, Error?) -> Void) {}
// FOO7: func foo7() async throws -> (String, Int) {
// FOO7-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO7-NEXT: foo7() { result1, result2, error in
// FOO7-NEXT: if let error = error {
// FOO7-NEXT: continuation.resume(throwing: error)
// FOO7-NEXT: return
// FOO7-NEXT: }
// FOO7-NEXT: guard let result1 = result1 else {
// FOO7-NEXT: fatalError("Expected non-nil result 'result1' for nil error")
// FOO7-NEXT: }
// FOO7-NEXT: continuation.resume(returning: (result1, result2))
// FOO7-NEXT: }
// FOO7-NEXT: }
// FOO7-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO8 %s
func foo8(_ completion: @escaping (String?, Int?, Error?) -> Void) {}
// FOO8: func foo8() async throws -> (String, Int) {
// FOO8-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO8-NEXT: foo8() { result1, result2, error in
// FOO8-NEXT: if let error = error {
// FOO8-NEXT: continuation.resume(throwing: error)
// FOO8-NEXT: return
// FOO8-NEXT: }
// FOO8-NEXT: guard let result1 = result1 else {
// FOO8-NEXT: fatalError("Expected non-nil result 'result1' for nil error")
// FOO8-NEXT: }
// FOO8-NEXT: guard let result2 = result2 else {
// FOO8-NEXT: fatalError("Expected non-nil result 'result2' for nil error")
// FOO8-NEXT: }
// FOO8-NEXT: continuation.resume(returning: (result1, result2))
// FOO8-NEXT: }
// FOO8-NEXT: }
// FOO8-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO9 %s
func foo9(_ completion: @escaping (Result<String, Error>) -> Void) {}
// FOO9: func foo9() async throws -> String {
// FOO9-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO9-NEXT: foo9() { result in
// FOO9-NEXT: continuation.resume(with: result)
// FOO9-NEXT: }
// FOO9-NEXT: }
// FOO9-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO10 %s
func foo10(arg: Int, _ completion: @escaping (Result<(String, Int), Error>) -> Void) {}
// FOO10: func foo10(arg: Int) async throws -> (String, Int) {
// FOO10-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO10-NEXT: foo10(arg: arg) { result in
// FOO10-NEXT: continuation.resume(with: result)
// FOO10-NEXT: }
// FOO10-NEXT: }
// FOO10-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO11 %s
func foo11(completion: @escaping (Result<String, Never>) -> Void) {}
// FOO11: func foo11() async -> String {
// FOO11-NEXT: return await withCheckedContinuation { continuation in
// FOO11-NEXT: foo11() { result in
// FOO11-NEXT: continuation.resume(with: result)
// FOO11-NEXT: }
// FOO11-NEXT: }
// FOO11-NEXT: }
// RUN: %refactor-check-compiles -add-async-wrapper -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=FOO12 %s
func foo12(completion: @escaping (Result<String, CustomError>) -> Void) {}
// FOO12: func foo12() async throws -> String {
// FOO12-NEXT: return try await withCheckedThrowingContinuation { continuation in
// FOO12-NEXT: foo12() { result in
// FOO12-NEXT: continuation.resume(with: result)
// FOO12-NEXT: }
// FOO12-NEXT: }
// FOO12-NEXT: }
|
0743f9a1362a016e83ded74464af5a82
| 43.611111 | 167 | 0.639975 | false | false | false | false |
nodes-ios/NStack
|
refs/heads/master
|
NStackSDK/NStackSDK/Classes/Model/IPAddress.swift
|
mit
|
1
|
//
// IPAddress.swift
// NStackSDK
//
// Created by Christian Graver on 01/11/2017.
// Copyright © 2017 Nodes ApS. All rights reserved.
//
import Serpent
public struct IPAddress {
public var ipStart = ""
public var ipEnd = ""
public var country = ""
public var stateProv = ""
public var city = ""
public var lat = ""
public var lng = ""
public var timeZoneOffset = ""
public var timeZoneName = ""
public var ispName = ""
public var connectionType = ""
public var type = ""
public var requestedIp = ""
}
extension IPAddress: Serializable {
public init(dictionary: NSDictionary?) {
ipStart <== (self, dictionary, "ip_start")
ipEnd <== (self, dictionary, "ip_end")
country <== (self, dictionary, "country")
stateProv <== (self, dictionary, "state_prov")
city <== (self, dictionary, "city")
lat <== (self, dictionary, "lat")
lng <== (self, dictionary, "lng")
timeZoneOffset <== (self, dictionary, "time_zone_offset")
timeZoneName <== (self, dictionary, "time_zone_name")
ispName <== (self, dictionary, "isp_name")
connectionType <== (self, dictionary, "connection_type")
type <== (self, dictionary, "type")
requestedIp <== (self, dictionary, "requested_ip")
}
public func encodableRepresentation() -> NSCoding {
let dict = NSMutableDictionary()
(dict, "ip_start") <== ipStart
(dict, "ip_end") <== ipEnd
(dict, "country") <== country
(dict, "state_prov") <== stateProv
(dict, "city") <== city
(dict, "lat") <== lat
(dict, "lng") <== lng
(dict, "time_zone_offset") <== timeZoneOffset
(dict, "time_zone_name") <== timeZoneName
(dict, "isp_name") <== ispName
(dict, "connection_type") <== connectionType
(dict, "type") <== type
(dict, "requested_ip") <== requestedIp
return dict
}
}
|
e3e06dee7f7241d229a140487366e11f
| 33.83871 | 65 | 0.518056 | false | false | false | false |
nicholas-richardson/swift3-treehouse
|
refs/heads/master
|
swift3-Basics/swift3-Basics.playground/Pages/Variables & Constants.xcplaygroundpage/Contents.swift
|
mit
|
1
|
// Variables
var str = "Hello, playground"
str = "Hello, world!"
var number = 10
number = 20
// Constants
let language = "Swift"
// Naming Conventions
// Rule #1: Spaces not allowed in varibale names
// let programming Language = "Objective-C" | Wrong!
// let programmingLanguage = "Objective-C" | Right!
// Rule #2: Use camle case
// let programminglanguage = "Objective-C" | Wrong!
// let programmingLanguage = "Objective-C" | Right!
|
e869f85184815a5667b821b9b3d3662d
| 20.238095 | 52 | 0.683857 | false | false | false | false |
huonw/swift
|
refs/heads/master
|
stdlib/public/core/HashedCollectionsAnyHashableExtensions.swift
|
apache-2.0
|
4
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Convenience APIs for Set<AnyHashable>
//===----------------------------------------------------------------------===//
extension Set where Element == AnyHashable {
@inlinable // FIXME(sil-serialize-all)
public mutating func insert<ConcreteElement : Hashable>(
_ newMember: ConcreteElement
) -> (inserted: Bool, memberAfterInsert: ConcreteElement) {
let (inserted, memberAfterInsert) =
insert(AnyHashable(newMember))
return (
inserted: inserted,
memberAfterInsert: memberAfterInsert.base as! ConcreteElement)
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func update<ConcreteElement : Hashable>(
with newMember: ConcreteElement
) -> ConcreteElement? {
return update(with: AnyHashable(newMember))
.map { $0.base as! ConcreteElement }
}
@inlinable // FIXME(sil-serialize-all)
@discardableResult
public mutating func remove<ConcreteElement : Hashable>(
_ member: ConcreteElement
) -> ConcreteElement? {
return remove(AnyHashable(member))
.map { $0.base as! ConcreteElement }
}
}
|
c4a7a4ad9f0b8a88591ce866bbeac1c1
| 35.913043 | 80 | 0.581861 | false | false | false | false |
linhaosunny/smallGifts
|
refs/heads/master
|
小礼品/小礼品/Classes/Module/Me/Views/CustomButton.swift
|
mit
|
1
|
//
// CustomButton.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/24.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
class CustomButton: UIButton {
//MARK: 重写布局
override func layoutSubviews() {
super.layoutSubviews()
let centerMargin = margin * 0.2
let imageOffsetY = (bounds.height - imageView!.bounds.height - titleLabel!.bounds.height - centerMargin) * 0.5
let imageOffsetX = (bounds.width - imageView!.bounds.width) * 0.5
let titleOffsetX = (bounds.width - titleLabel!.bounds.width) * 0.5
imageView!.frame.origin.y = imageOffsetY
imageView!.frame.origin.x = imageOffsetX
titleLabel!.frame.origin.y = imageView!.frame.maxY + centerMargin
titleLabel!.frame.origin.x = titleOffsetX
}
}
|
fffd265d69fe2e589ac4b058a2ea1b26
| 24.969697 | 118 | 0.621937 | false | false | false | false |
iOSDevLog/InkChat
|
refs/heads/master
|
InkChat/InkChat/Profile/Controller/SettingsTableViewController.swift
|
apache-2.0
|
1
|
//
// SettingsTableViewController.swift
// InkChat
//
// Created by iOS Dev Log on 2017/5/28.
// Copyright © 2017年 iOSDevLog. All rights reserved.
//
import UIKit
class SettingsTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "section0", for: indexPath)
if indexPath.row == 0 {
cell.textLabel?.text = "About"
} else {
var userType = "unknow"
if let type = ad.user?.type {
userType = type
cell.textLabel?.text = "Your're \(String(describing: userType))"
}
}
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "section1", for: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 {
User.logOutUser(completion: { (status) in
if status {
self.dismiss(animated: true, completion: nil)
}
})
} else if (indexPath.section == 0) && (indexPath.row == 1) && ad.user?.type == "artist" {
self.performSegue(withIdentifier: "PriceSegue", sender: nil)
}
}
}
|
84bef1d44744645af4d94e55f2b24102
| 28.753623 | 109 | 0.56113 | false | false | false | false |
lkzhao/Hero
|
refs/heads/master
|
LegacyExamples/Examples/AppleHomePage/AppleProductViewController.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// 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
import Hero
let viewControllerIDs = ["iphone", "watch", "macbook"]
class AppleProductViewController: UIViewController, HeroViewControllerDelegate {
var panGR: UIPanGestureRecognizer!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var primaryLabel: UILabel!
@IBOutlet weak var secondaryLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
panGR = UIPanGestureRecognizer(target: self, action: #selector(pan))
view.addGestureRecognizer(panGR)
}
func applyShrinkModifiers() {
view.hero.modifiers = nil
primaryLabel.hero.modifiers = [.translate(x:-50, y:(view.center.y - primaryLabel.center.y)/10), .scale(0.9), HeroModifier.duration(0.3)]
secondaryLabel.hero.modifiers = [.translate(x:-50, y:(view.center.y - secondaryLabel.center.y)/10), .scale(0.9), HeroModifier.duration(0.3)]
imageView.hero.modifiers = [.translate(x:-80), .scale(0.9), HeroModifier.duration(0.3)]
}
func applySlideModifiers() {
view.hero.modifiers = [.translate(x: view.bounds.width), .duration(0.3), .beginWith(modifiers: [.zPosition(2)])]
primaryLabel.hero.modifiers = [.translate(x:100), .duration(0.3)]
secondaryLabel.hero.modifiers = [.translate(x:100), .duration(0.3)]
imageView.hero.modifiers = nil
}
enum TransitionState {
case normal, slidingLeft, slidingRight
}
var state: TransitionState = .normal
weak var nextVC: AppleProductViewController?
@objc func pan() {
let translateX = panGR.translation(in: nil).x
let velocityX = panGR.velocity(in: nil).x
switch panGR.state {
case .began, .changed:
let nextState: TransitionState
if state == .normal {
nextState = velocityX < 0 ? .slidingLeft : .slidingRight
} else {
nextState = translateX < 0 ? .slidingLeft : .slidingRight
}
if nextState != state {
Hero.shared.cancel(animate: false)
let currentIndex = viewControllerIDs.index(of: self.title!)!
let nextIndex = (currentIndex + (nextState == .slidingLeft ? 1 : viewControllerIDs.count - 1)) % viewControllerIDs.count
nextVC = self.storyboard!.instantiateViewController(withIdentifier: viewControllerIDs[nextIndex]) as? AppleProductViewController
if nextState == .slidingLeft {
applyShrinkModifiers()
nextVC!.applySlideModifiers()
} else {
applySlideModifiers()
nextVC!.applyShrinkModifiers()
}
state = nextState
hero.replaceViewController(with: nextVC!)
} else {
let progress = abs(translateX / view.bounds.width)
Hero.shared.update(progress)
if state == .slidingLeft, let nextVC = nextVC {
Hero.shared.apply(modifiers: [.translate(x: view.bounds.width + translateX)], to: nextVC.view)
} else {
Hero.shared.apply(modifiers: [.translate(x: translateX)], to: view)
}
}
default:
let progress = (translateX + velocityX) / view.bounds.width
if (progress < 0) == (state == .slidingLeft) && abs(progress) > 0.3 {
Hero.shared.finish()
} else {
Hero.shared.cancel()
}
state = .normal
}
}
func heroWillStartAnimatingTo(viewController: UIViewController) {
if !(viewController is AppleProductViewController) {
view.hero.modifiers = [.ignoreSubviewModifiers(recursive: true)]
}
}
}
|
22acc6d3f29947a5912eb20fb4449e3f
| 38.850877 | 144 | 0.690073 | false | false | false | false |
mysangle/algorithm-study
|
refs/heads/master
|
wiggle-subsequence/WiggleSubsequence.swift
|
mit
|
1
|
/**
* wiggleMaxLength: Time Limit Exceeded
* wiggleMaxLength2: ok
*/
func wiggleMaxLength(_ nums: [Int]) -> Int {
return iWiggleMaxLength(nums, 0, 0)
}
func iWiggleMaxLength(_ nums: [Int], _ index: Int, _ maxlen: Int) -> Int {
if nums.count == index {
if maxlen >= nums.count {
return maxlen
}
let count = calWiggle(nums)
print("\(nums): \(count) - \(maxlen)")
return count
}
let include = iWiggleMaxLength(nums, index+1, maxlen)
if include >= index {
var newNums = nums
newNums.remove(at: index)
let m = max(include, maxlen)
let exclude = iWiggleMaxLength(newNums, index, m)
return max(include, exclude)
}
return include
}
func calWiggle(_ nums: [Int]) -> Int {
if nums.count < 2 {
return nums.count
}
if nums.count == 2 {
if nums[0] != nums[1] {
return 2
} else {
return 1
}
}
var count = 1
var prev = 0
var middle = 1
var next = 2
var f = nums[prev] < nums[middle]
while nums[prev] != nums[middle] {
count += 1
let s = nums[middle] < nums[next]
if f == s {
break
}
prev += 1
middle += 1
next += 1
f = s
if nums.count == next {
count += 1
break
}
}
return count
}
func wiggleMaxLength2(_ nums: [Int]) -> Int {
if nums.count < 2 {
return nums.count
}
var count = 0
var diff = 0
for index in 1..<nums.count {
if nums[index-1] != nums[index] {
if nums[index-1] < nums[index] {
if diff <= 0 {
count += 1
}
diff = 1
} else {
if diff >= 0 {
count += 1
}
diff = -1
}
}
}
return count + 1
}
|
18c0e05dcc95d5c42965ee05e53cd761
| 20.868132 | 74 | 0.446734 | false | false | false | false |
fgengine/quickly
|
refs/heads/master
|
Quickly/Views/Labels/QLinkLabel.swift
|
mit
|
1
|
//
// Quickly
//
open class QLinkLabel : QLabel {
public typealias PressedClosure = (_ label: QLinkLabel, _ link: QLinkLabel.Link) -> Void
public class Link {
public var range: Range< String.Index >
public var normal: QTextStyle
public var highlight: QTextStyle?
public var onPressed: PressedClosure
public var isHighlighted: Bool
public init(_ range: Range< String.Index >, normal: QTextStyle, highlight: QTextStyle?, onPressed: @escaping PressedClosure) {
self.range = range
self.normal = normal
self.highlight = highlight
self.onPressed = onPressed
self.isHighlighted = false
}
public func attributes() -> [NSAttributedString.Key: Any] {
if self.isHighlighted == true {
if let highlight = self.highlight {
return highlight.attributes
}
}
return self.normal.attributes
}
}
public private(set) var pressGestureRecognizer: UILongPressGestureRecognizer? {
willSet {
if let gestureRecognizer = self.pressGestureRecognizer {
self.removeGestureRecognizer(gestureRecognizer)
}
}
didSet {
if let gestureRecognizer = self.pressGestureRecognizer {
self.addGestureRecognizer(gestureRecognizer)
}
}
}
public var links: [Link] = [] {
didSet { self._updateTextStorage() }
}
public func appendLink(_ string: String, normal: QTextStyle, highlight: QTextStyle?, onPressed: @escaping PressedClosure) {
guard let text = self.text else { return }
guard let range = text.attributed.string.range(of: string) else { return }
self.links.append(Link(range, normal: normal, highlight: highlight, onPressed: onPressed))
self._updateTextStorage()
}
public func appendLink(_ range: Range< String.Index >, normal: QTextStyle, highlight: QTextStyle?, onPressed: @escaping PressedClosure) {
self.links.append(Link(range, normal: normal, highlight: highlight, onPressed: onPressed))
self._updateTextStorage()
}
public func removeLink(_ range: Range< String.Index >) {
var removeIndeces: [Int] = []
var index: Int = 0
for link in self.links {
if range.overlaps(link.range) == true {
removeIndeces.append(index)
}
index += 1
}
for removeIndex in removeIndeces {
self.links.remove(at: removeIndex)
}
self._updateTextStorage()
}
public func removeAllLinks() {
self.links.removeAll()
self._updateTextStorage()
}
@IBAction private func handlePressGesture(_ gesture: UILongPressGestureRecognizer) {
var needUpdate = false
let point = gesture.location(in: self)
if let charecterIndex = self.characterIndex(point: point) {
for link in self.links {
let highlighted = link.range.contains(charecterIndex)
if link.isHighlighted != highlighted {
link.isHighlighted = highlighted
needUpdate = true
}
}
} else {
for link in self.links {
if link.isHighlighted == true {
link.isHighlighted = false
needUpdate = true
}
}
}
switch gesture.state {
case .ended:
for link in self.links {
if link.isHighlighted == true {
link.onPressed(self, link)
}
}
default: break
}
if needUpdate == true {
self._updateTextStorage()
}
}
open override func setup() {
super.setup()
self.isUserInteractionEnabled = true
let gestureRecognizer = UILongPressGestureRecognizer(
target: self,
action: #selector(self.handlePressGesture(_:))
)
gestureRecognizer.delaysTouchesBegan = true
gestureRecognizer.minimumPressDuration = 0.01
self.pressGestureRecognizer = gestureRecognizer
}
internal override func _updateTextStorage() {
super._updateTextStorage()
let string = self.textStorage.string
let stringRange = string.startIndex ..< string.endIndex
for link in self.links {
let stringRange = stringRange.clamped(to: link.range)
let nsRange = string.nsRange(from: stringRange)
let attributes = link.attributes()
self.textStorage.setAttributes(attributes, range: nsRange)
}
}
}
|
3919d6a3d436da0d487e88df7cdca2c0
| 32.180556 | 141 | 0.580578 | false | false | false | false |
stripe/stripe-ios
|
refs/heads/master
|
StripePayments/StripePayments/API Bindings/Models/PaymentMethods/Types/STPPaymentMethodCardWalletVisaCheckout.swift
|
mit
|
1
|
//
// STPPaymentMethodCardWalletVisaCheckout.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 3/9/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// A Visa Checkout Card Wallet
/// - seealso: https://stripe.com/docs/visa-checkout
public class STPPaymentMethodCardWalletVisaCheckout: NSObject, STPAPIResponseDecodable {
/// Owner’s verified email. Values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement.
@objc public private(set) var email: String?
/// Owner’s verified email. Values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement.
@objc public private(set) var name: String?
/// Owner’s verified billing address. Values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement.
@objc public private(set) var billingAddress: STPPaymentMethodAddress?
/// Owner’s verified shipping address. Values are verified or provided by the payment method directly (and if supported) at the time of authorization or settlement.
@objc public private(set) var shippingAddress: STPPaymentMethodAddress?
private(set) public var allResponseFields: [AnyHashable: Any] = [:]
override required init() {
super.init()
}
// MARK: - STPAPIResponseDecodable
public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? {
guard let response = response else {
return nil
}
let dict = response.stp_dictionaryByRemovingNulls()
let visaCheckout = self.init()
visaCheckout.allResponseFields = response
visaCheckout.billingAddress = STPPaymentMethodAddress.decodedObject(
fromAPIResponse: dict.stp_dictionary(forKey: "billing_address")
)
visaCheckout.shippingAddress = STPPaymentMethodAddress.decodedObject(
fromAPIResponse: dict.stp_dictionary(forKey: "shipping_address")
)
visaCheckout.email = dict.stp_string(forKey: "email")
visaCheckout.name = dict.stp_string(forKey: "name")
return visaCheckout
}
}
|
3777a946c77d3e8262b740460ae36b8f
| 46.787234 | 168 | 0.719947 | false | false | false | false |
AlexBianzd/NiceApp
|
refs/heads/master
|
DYTV-AlexanderZ-Swift/Pods/Kingfisher/Sources/ImageProcessor.swift
|
apache-2.0
|
12
|
//
// ImageProcessor.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/26.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// 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 CoreGraphics
/// The item which could be processed by an `ImageProcessor`
///
/// - image: Input image
/// - data: Input data
public enum ImageProcessItem {
case image(Image)
case data(Data)
}
/// An `ImageProcessor` would be used to convert some downloaded data to an image.
public protocol ImageProcessor {
/// Identifier of the processor. It will be used to identify the processor when
/// caching and retriving an image. You might want to make sure that processors with
/// same properties/functionality have the same identifiers, so correct processed images
/// could be retrived with proper key.
///
/// - Note: Do not supply an empty string for a customized processor, which is already taken by
/// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation
/// string of your own for the identifier.
var identifier: String { get }
/// Process an input `ImageProcessItem` item to an image for this processor.
///
/// - parameter item: Input item which will be processed by `self`
/// - parameter options: Options when processing the item.
///
/// - returns: The processed image.
///
/// - Note: The return value will be `nil` if processing failed while converting data to image.
/// If input item is already an image and there is any errors in processing, the input
/// image itself will be returned.
/// - Note: Most processor only supports CG-based images.
/// watchOS is not supported for processers containing filter, the input image will be returned directly on watchOS.
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
}
typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?)
public extension ImageProcessor {
/// Append an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
/// will be "\(self.identifier)|>\(another.identifier)>".
///
/// - parameter another: An `ImageProcessor` you want to append to `self`.
///
/// - returns: The new `ImageProcessor`. It will process the image in the order
/// of the two processors concatenated.
public func append(another: ImageProcessor) -> ImageProcessor {
let newIdentifier = identifier.appending("|>\(another.identifier)")
return GeneralProcessor(identifier: newIdentifier) {
item, options in
if let image = self.process(item: item, options: options) {
return another.process(item: .image(image), options: options)
} else {
return nil
}
}
}
}
fileprivate struct GeneralProcessor: ImageProcessor {
let identifier: String
let p: ProcessorImp
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
return p(item, options)
}
}
/// The default processor. It convert the input data to a valid image.
/// Images of .PNG, .JPEG and .GIF format are supported.
/// If an image is given, `DefaultImageProcessor` will do nothing on it and just return that image.
public struct DefaultImageProcessor: ImageProcessor {
/// A default `DefaultImageProcessor` could be used across.
public static let `default` = DefaultImageProcessor()
public let identifier = ""
/// Initialize a `DefaultImageProcessor`
///
/// - returns: An initialized `DefaultImageProcessor`.
public init() {}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image
case .data(let data):
return Kingfisher<Image>.image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData)
}
}
}
/// Processor for making round corner images. Only CG-based images are supported in macOS,
/// if a non-CG image passed in, the processor will do nothing.
public struct RoundCornerImageProcessor: ImageProcessor {
public let identifier: String
/// Corner radius will be applied in processing.
public let cornerRadius: CGFloat
/// Target size of output image should be. If `nil`, the image will keep its original size after processing.
public let targetSize: CGSize?
/// Initialize a `RoundCornerImageProcessor`
///
/// - parameter cornerRadius: Corner radius will be applied in processing.
/// - parameter targetSize: Target size of output image should be. If `nil`,
/// the image will keep its original size after processing.
/// Default is `nil`.
///
/// - returns: An initialized `RoundCornerImageProcessor`.
public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) {
self.cornerRadius = cornerRadius
self.targetSize = targetSize
if let size = targetSize {
self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius)_\(size))"
} else {
self.identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(cornerRadius))"
}
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
let size = targetSize ?? image.kf.size
return image.kf.image(withRoundRadius: cornerRadius, fit: size, scale: options.scaleFactor)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for resizing images. Only CG-based images are supported in macOS.
public struct ResizingImageProcessor: ImageProcessor {
public let identifier: String
/// Target size of output image should be.
public let targetSize: CGSize
/// Initialize a `ResizingImageProcessor`
///
/// - parameter targetSize: Target size of output image should be.
///
/// - returns: An initialized `ResizingImageProcessor`.
public init(targetSize: CGSize) {
self.targetSize = targetSize
self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(targetSize))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.resize(to: targetSize)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
/// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
public struct BlurImageProcessor: ImageProcessor {
public let identifier: String
/// Blur radius for the simulated Gaussian blur.
public let blurRadius: CGFloat
/// Initialize a `BlurImageProcessor`
///
/// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
///
/// - returns: An initialized `BlurImageProcessor`.
public init(blurRadius: CGFloat) {
self.blurRadius = blurRadius
self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
let radius = blurRadius * options.scaleFactor
return image.kf.blurred(withRadius: radius)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
public struct OverlayImageProcessor: ImageProcessor {
public var identifier: String
/// Overlay color will be used to overlay the input image.
public let overlay: Color
/// Fraction will be used when overlay the color to image.
public let fraction: CGFloat
/// Initialize an `OverlayImageProcessor`
///
/// - parameter overlay: Overlay color will be used to overlay the input image.
/// - parameter fraction: Fraction will be used when overlay the color to image.
/// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
///
/// - returns: An initialized `OverlayImageProcessor`.
public init(overlay: Color, fraction: CGFloat = 0.5) {
self.overlay = overlay
self.fraction = fraction
self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.overlaying(with: overlay, fraction: fraction)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for tint images with color. Only CG-based images are supported.
public struct TintImageProcessor: ImageProcessor {
public let identifier: String
/// Tint color will be used to tint the input image.
public let tint: Color
/// Initialize a `TintImageProcessor`
///
/// - parameter tint: Tint color will be used to tint the input image.
///
/// - returns: An initialized `TintImageProcessor`.
public init(tint: Color) {
self.tint = tint
self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.tinted(with: tint)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for applying some color control to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct ColorControlsProcessor: ImageProcessor {
public let identifier: String
/// Brightness changing to image.
public let brightness: CGFloat
/// Contrast changing to image.
public let contrast: CGFloat
/// Saturation changing to image.
public let saturation: CGFloat
/// InputEV changing to image.
public let inputEV: CGFloat
/// Initialize a `ColorControlsProcessor`
///
/// - parameter brightness: Brightness changing to image.
/// - parameter contrast: Contrast changing to image.
/// - parameter saturation: Saturation changing to image.
/// - parameter inputEV: InputEV changing to image.
///
/// - returns: An initialized `ColorControlsProcessor`
public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.inputEV = inputEV
self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
case .data(_):
return (DefaultImageProcessor() >> self).process(item: item, options: options)
}
}
}
/// Processor for applying black and white effect to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct BlackWhiteProcessor: ImageProcessor {
public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
/// Initialize a `BlackWhiteProcessor`
///
/// - returns: An initialized `BlackWhiteProcessor`
public init() {}
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
.process(item: item, options: options)
}
}
/// Concatenate two `ImageProcessor`s. `ImageProcessor.appen(another:)` is used internally.
///
/// - parameter left: First processor.
/// - parameter right: Second processor.
///
/// - returns: The concatenated processor.
public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
return left.append(another: right)
}
fileprivate extension Color {
var hex: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rInt = Int(r * 255) << 24
let gInt = Int(g * 255) << 16
let bInt = Int(b * 255) << 8
let aInt = Int(a * 255)
let rgba = rInt | gInt | bInt | aInt
return String(format:"#%08x", rgba)
}
}
|
0c65c060c75f6eb26a5a7a063ae30bf4
| 37.997297 | 128 | 0.662069 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
refs/heads/master
|
arcgis-ios-sdk-samples/Content Display Logic/Model/SearchEngine.swift
|
apache-2.0
|
1
|
// Copyright 2016 Esri.
//
// 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 UIKit
class SearchEngine: NSObject {
static private let singleton = SearchEngine()
private var indexArray:[String]!
private var wordsDictionary:[String: [String]]!
private var isLoading = false
override init() {
super.init()
self.commonInit()
}
static func sharedInstance() -> SearchEngine {
return singleton
}
private func commonInit() {
if !self.isLoading {
self.isLoading = true
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { [weak self] () -> Void in
guard let weakSelf = self else {
return
}
//get the directory URLs that contain readme files
let readmeDirectoriesURLs = weakSelf.findReadmeDirectoriesURLs()
//index the content of all the readme files
weakSelf.indexAllReadmes(readmeDirectoriesURLs)
self?.isLoading = false
}
}
}
private func findReadmeDirectoriesURLs() -> [NSURL] {
var readmeDirectoriesURLs = [NSURL]()
let fileManager = NSFileManager.defaultManager()
let bundleURL = NSBundle.mainBundle().bundleURL
//get all the directories from the bundle
let directoryEnumerator = fileManager.enumeratorAtURL(bundleURL, includingPropertiesForKeys: [NSURLNameKey, NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil)
//check if the returned url is of a directory
if let directoryEnumerator = directoryEnumerator {
while let fileURL = directoryEnumerator.nextObject() as? NSURL {
var isDirectory:AnyObject?
do {
try fileURL.getResourceValue(&isDirectory, forKey: NSURLIsDirectoryKey)
} catch {
print("throws")
}
//check if the directory contains a readme file
if let isDirectory = isDirectory as? NSNumber where isDirectory.boolValue == true {
let readmePath = "\(fileURL.path!)/README.md"
if fileManager.fileExistsAtPath(readmePath) {
readmeDirectoriesURLs.append(fileURL)
}
}
}
}
return readmeDirectoriesURLs
}
private func indexAllReadmes(readmeDirectoriesURLs:[NSURL]) {
self.indexArray = [String]()
self.wordsDictionary = [String: [String]]()
let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagSchemeTokenType, NSLinguisticTagSchemeNameType, NSLinguisticTagSchemeLexicalClass], options: 0)
for directoryURL in readmeDirectoriesURLs {
autoreleasepool {
if let contentString = self.contentOfReadmeFile(directoryURL.path!) {
//sample display name
let sampleDisplayName = directoryURL.path!.componentsSeparatedByString("/").last!
tagger.string = contentString
let range = NSMakeRange(0, contentString.characters.count)
tagger.enumerateTagsInRange(range, scheme: NSLinguisticTagSchemeLexicalClass, options: [NSLinguisticTaggerOptions.OmitWhitespace, NSLinguisticTaggerOptions.OmitPunctuation], usingBlock: { (tag:String, tokenRange:NSRange, sentenceRange:NSRange, _) -> Void in
if tag == NSLinguisticTagNoun || tag == NSLinguisticTagVerb || tag == NSLinguisticTagAdjective || tag == NSLinguisticTagOtherWord {
let word = (contentString as NSString).substringWithRange(tokenRange) as String
//trivial comparisons
if word != "`." && word != "```" && word != "`" {
var samples = self.wordsDictionary[word]
//if word already exists in the dictionary
if samples != nil {
//add the sample display name to the list if not already present
if !(samples!.contains(sampleDisplayName)) {
samples!.append(sampleDisplayName)
self.wordsDictionary[word] = samples
}
}
else {
samples = [sampleDisplayName]
self.wordsDictionary[word] = samples
}
//add to the index
if !self.indexArray.contains(word) {
self.indexArray.append(word)
}
}
}
})
}
}
}
}
private func contentOfReadmeFile(directoryPath:String) -> String? {
//find the path of the file
let path = "\(directoryPath)/README.md"
//read the content of the file
if let content = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding) {
return content
}
return nil
}
//MARK: - Public methods
func searchForString(string:String) -> [String]? {
//if the resources where released because of memory warnings
if self.indexArray == nil {
self.commonInit()
return nil
}
//check if the string exists in the index array
let words = self.indexArray.filter({ $0.uppercaseString == string.uppercaseString })
if words.count > 0 {
if let sampleDisplayNames = self.wordsDictionary[words[0]] {
return sampleDisplayNames
}
}
return nil
}
func suggestionsForString(string:String) -> [String]? {
//if the resources where released because of memory warnings
if self.indexArray == nil {
self.commonInit()
return nil
}
let suggestions = self.indexArray.filter( { $0.uppercaseString.rangeOfString(string.uppercaseString) != nil } )
return suggestions
}
}
|
6b1196288bd767c24a306994bc991c82
| 40.264368 | 277 | 0.547911 | false | false | false | false |
lucianomarisi/JSONUtilities
|
refs/heads/master
|
Sources/JSONUtilities/DecodingError.swift
|
mit
|
1
|
//
// Errors.swift
// JSONUtilities
//
// Created by Luciano Marisi on 05/03/2016.
// Copyright © 2016 Luciano Marisi All rights reserved.
//
import Foundation
/**
Error that occurs when decoding
*/
public struct DecodingError: Error, CustomStringConvertible, CustomDebugStringConvertible {
/// The reason the error occurred
public var reason: Reason
/// dictionary in which the error occured
public let dictionary: [AnyHashable: Any]
/// array in which the error occurred
public let array: JSONArray?
/// the keypath at which the error occurred
public let keyPath: String
/// the expected type that was being decoded while the error happened
public let expectedType: Any
/// the value that caused the error
public let value: Any
public init(dictionary: [AnyHashable: Any], keyPath: StringProtocol, expectedType: Any.Type, value: Any, array: JSONArray? = nil, reason: Reason) {
self.dictionary = dictionary
self.keyPath = keyPath.string
self.expectedType = expectedType
self.value = value
self.reason = reason
self.array = array
}
var reasonDescription: String {
switch reason {
case .keyNotFound:
return "Nothing found"
case .incorrectRawRepresentableRawValue:
return "Incorrect rawValue of \(value) for \(expectedType)"
case .incorrectType:
return "Incorrect type, expected \(expectedType) found \(value)"
case .conversionFailure:
return "\(expectedType) failed to convert \(value)"
}
}
public var description: String {
return "Decoding failed at \"\(keyPath)\": \(reasonDescription)"
}
public var debugDescription: String {
return "\(description):\n\(array?.description ?? dictionary.description)"
}
/// The reason the error occurred
public enum Reason: String, CustomStringConvertible {
/// Key was not found in a JSONDictionary
case keyNotFound = "Key not found"
/// A value was found that can't initialise a RawRepresentable. In the case of an enum, the rawValue did not match any of the case's rawValue
case incorrectRawRepresentableRawValue = "Incorrect RawRepresentable RawValue"
/// The value has the incorrect type
case incorrectType = "Incorrect type"
/// A JSONPrimitiveConvertible failed to convert
case conversionFailure = "Conversion failure"
public var description: String {
return rawValue
}
}
}
|
6a7d259a90cb7fa4f8a2bed7fde5bba7
| 28.036145 | 149 | 0.709544 | false | false | false | false |
AppriaTT/Swift_SelfLearning
|
refs/heads/master
|
Swift/swift15 animateSplash/swift15 animateSplash/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// swift15 animateSplash
//
// Created by Aaron on 16/7/15.
// Copyright © 2016年 Aaron. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var mask: CALayer?
var imageView:UIImageView?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = UIViewController()
self.window?.makeKeyAndVisible()
//充当底部内容简介 后期可以用tabbarController.view替换
let imgView = UIImageView(image: UIImage(named: "screen"))
imgView.frame = self.window!.bounds
self.window?.addSubview(imgView)
//中间充当mask的小鸟
mask = CALayer()
mask!.contents = UIImage(named: "twitter")?.CGImage
mask?.contentsGravity = kCAGravityResizeAspect
mask?.bounds = CGRectMake(0, 0, 100, 81)
mask?.anchorPoint = CGPoint(x: 0.5, y: 0.5)
mask?.position = CGPoint(x: imgView.frame.size.width / 2, y: imgView.frame.height / 2)
imgView.layer.mask = mask
self.imageView = imgView
self.animateMask()
self.window!.backgroundColor = UIColor(red:0.117, green:0.631, blue:0.949, alpha:1)
// Override point for customization after application launch.
return true
}
func animateMask(){
let keyFrameAnimation = CAKeyframeAnimation(keyPath: "bounds")
keyFrameAnimation.delegate = self
keyFrameAnimation.duration = 0.6
keyFrameAnimation.beginTime = CACurrentMediaTime() + 0.5
keyFrameAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)]
//三段动画 我的理解是为了展现小鸟震动的效果, 先缩小再放大至空白部分填满全屏
let initalBounds = NSValue(CGRect: mask!.bounds)
let secondBounds = NSValue(CGRect:CGRect(x: 0, y: 0, width: 90, height: 73))
let finalBounds = NSValue(CGRect:CGRect(x: 0, y: 0, width: 1600, height: 1300))
keyFrameAnimation.values = [initalBounds,secondBounds,finalBounds]
keyFrameAnimation.keyTimes = [0,0.3,1]
self.mask?.addAnimation(keyFrameAnimation, forKey: "bounds")
}
override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
//动画结束后取消遮罩
self.imageView!.layer.mask = nil
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
8fc021e71f59df5783f4cfec087f5947
| 45.417582 | 285 | 0.703835 | false | false | false | false |
iOSDevLog/iOSDevLog
|
refs/heads/master
|
169. Camera/Camera/ExposureViewController.swift
|
mit
|
1
|
//
// ExposureViewController.swift
// Camera
//
// Created by Matteo Caldari on 05/02/15.
// Copyright (c) 2015 Matteo Caldari. All rights reserved.
//
import UIKit
import CoreMedia
class ExposureViewController: UIViewController, CameraControlsViewControllerProtocol, CameraSettingValueObserver {
@IBOutlet var modeSwitch:UISwitch!
@IBOutlet var biasSlider:UISlider!
@IBOutlet var durationSlider:UISlider!
@IBOutlet var isoSlider:UISlider!
var cameraController:CameraController? {
willSet {
if let cameraController = cameraController {
cameraController.unregisterObserver(self, property: CameraControlObservableSettingExposureTargetOffset)
cameraController.unregisterObserver(self, property: CameraControlObservableSettingExposureDuration)
cameraController.unregisterObserver(self, property: CameraControlObservableSettingISO)
}
}
didSet {
if let cameraController = cameraController {
cameraController.registerObserver(self, property: CameraControlObservableSettingExposureTargetOffset)
cameraController.registerObserver(self, property: CameraControlObservableSettingExposureDuration)
cameraController.registerObserver(self, property: CameraControlObservableSettingISO)
}
}
}
override func viewDidLoad() {
setInitialValues()
}
@IBAction func modeSwitchValueChanged(sender:UISwitch) {
if sender.on {
cameraController?.enableContinuousAutoExposure()
}
else {
cameraController?.setCustomExposureWithDuration(durationSlider.value)
}
updateSliders()
}
@IBAction func sliderValueChanged(sender:UISlider) {
switch sender {
case biasSlider:
cameraController?.setExposureTargetBias(sender.value)
case durationSlider:
cameraController?.setCustomExposureWithDuration(sender.value)
case isoSlider:
cameraController?.setCustomExposureWithISO(sender.value)
default: break
}
}
func cameraSetting(setting: String, valueChanged value: AnyObject) {
if setting == CameraControlObservableSettingExposureDuration {
if let durationValue = value as? NSValue {
let duration = CMTimeGetSeconds(durationValue.CMTimeValue)
durationSlider.value = Float(duration)
}
}
else if setting == CameraControlObservableSettingISO {
if let iso = value as? Float {
isoSlider.value = Float(iso)
}
}
}
func setInitialValues() {
if isViewLoaded() && cameraController != nil {
if let autoExposure = cameraController?.isContinuousAutoExposureEnabled() {
modeSwitch.on = autoExposure
updateSliders()
}
if let currentDuration = cameraController?.currentExposureDuration() {
durationSlider.value = currentDuration
}
if let currentISO = cameraController?.currentISO() {
isoSlider.value = currentISO
}
if let currentBias = cameraController?.currentExposureTargetOffset() {
biasSlider.value = currentBias
}
}
}
func updateSliders() {
for slider in [durationSlider, isoSlider] as [UISlider] {
slider.enabled = !modeSwitch.on
}
}
}
|
1e1bef2c5ca4841ec490b4ba1abfc66e
| 26.851852 | 114 | 0.762633 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT
|
refs/heads/master
|
WeiBo/WeiBo/Classes/View(视图)/NewFetureAndWelcomeView(新特性和欢迎界面)/WBWelcomeView.swift
|
mit
|
1
|
//
// WBWelcomeView.swift
// WeiBo
//
// Created by chenWei on 2017/4/5.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
import SDWebImage
class WBWelcomeView: UIView {
//头像
lazy var iconView: UIImageView = {
let imageView = UIImageView()
imageView.sd_setImage(with: URL(string: WBUserAccount.shared.avatar_large!)!, placeholderImage: UIImage(named: "avatar_default_big")!)
return imageView
}()
//欢迎文字的label
lazy var welcomeLabel: UILabel = UILabel(title: "欢迎归来, \(WBUserAccount.shared.screen_name!)", fontSize: 15, alignment: .center)
//已经添加到视图
override func didMoveToWindow() {
super.didMoveToWindow()
//添加动画
addAnimation()
}
override init(frame: CGRect) {
super.init(frame: screenBounds)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 创建 UI
extension WBWelcomeView {
func setupUI() {
self.backgroundColor = UIColor.white
//0. 给头像设圆角
iconView.layer.cornerRadius = 45
iconView.layer.masksToBounds = true
//1. 添加子视图
addSubview(iconView)
addSubview(welcomeLabel)
//2. 自动布局
iconView.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(-120)
make.size.equalTo(CGSize(width: 90, height: 90))
}
welcomeLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.bottom.equalTo(self).offset(-150)
}
//在动画执行之前,需要先强制执行布局 UI(执行 layoutIfNeeded),在这个方法调用之后,上面的布局才会生效
layoutIfNeeded()
}
//添加动画
func addAnimation() {
//更新头像的约束
iconView.snp.updateConstraints { (make) in
make.centerY.equalTo(self).offset(-150)
}
//usingSpringWithDamping: 弹力系数, 越小越弹
//initialSpringVelocity: 重力系数
UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 9.8, options: [], animations: {
self.layoutIfNeeded()
}) { (isFinish) in
self.removeFromSuperview()
}
}
}
|
5d09fb07f41d168b5ddfb8506572bdee
| 19.641026 | 142 | 0.564389 | false | false | false | false |
jkolb/Shkadov
|
refs/heads/master
|
Sources/Logger/LogRecord.swift
|
mit
|
1
|
/*
The MIT License (MIT)
Copyright (c) 2016 Justin Kolb
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.
*/
public struct LogRecord {
public let formattedTimestamp: String
public let level: LogLevel
public let name: String
public let threadID: UInt64
public let fileName: String
public let lineNumber: Int
public let message: String
public init(formattedTimestamp: String, level: LogLevel, name: String, threadID: UInt64, fileName: String, lineNumber: Int, message: String) {
self.formattedTimestamp = formattedTimestamp
self.level = level
self.name = name
self.threadID = threadID
self.fileName = fileName
self.lineNumber = lineNumber
self.message = message
}
}
|
1d7499cc1ede3a787efb33c71f8d2143
| 39.906977 | 146 | 0.744741 | false | false | false | false |
SimonFairbairn/Stormcloud
|
refs/heads/master
|
Sources/Stormcloud/Stormcloud.swift
|
mit
|
1
|
//
// Stormcloud.swift
// Stormcloud
//
// Created by Simon Fairbairn on 19/10/2015.
// Copyright © 2015 Simon Fairbairn. All rights reserved.
//
import UIKit
import CoreData
protocol StormcloudDocument {
var backupMetadata : StormcloudMetadata? {
get set
}
}
public typealias StormcloudDocumentClosure = (_ error : StormcloudError?, _ metadata : StormcloudMetadata?) -> ()
public protocol StormcloudRestoreDelegate : class {
func stormcloud( stormcloud : Stormcloud, shouldRestore objects: [String : AnyObject], toEntityWithName name: String ) -> Bool
}
enum StormcloudEntityKeys : String {
case EntityType = "com.voyagetravelapps.Stormcloud.entityType"
case ManagedObject = "com.voyagetravelapps.Stormcloud.managedObject"
}
// Keys for NSUSserDefaults that manage iCloud state
public enum StormcloudPrefKey : String {
case isUsingiCloud = "com.voyagetravelapps.Stormcloud.usingiCloud"
}
/**
* Informs the delegate of changes made to the metadata list.
*/
public protocol StormcloudDelegate : class {
func metadataDidUpdate( _ metadata : StormcloudMetadata, for type : StormcloudDocumentType)
func metadataListDidChange(_ manager : Stormcloud)
func metadataListDidAddItemsAt( _ addedItems : IndexSet?, andDeletedItemsAt deletedItems: IndexSet?, for type : StormcloudDocumentType)
func stormcloudFileListDidLoad( _ stormcloud : Stormcloud)
}
extension Stormcloud : DocumentProviderDelegate {
func provider(_ prov: DocumentProvider, didDelete item: URL) {
}
func provider(_ prov: DocumentProvider, didFindItems items: [StormcloudDocumentType : [StormcloudMetadata]]) {
if !fileListLoaded {
self.delegate?.stormcloudFileListDidLoad(self)
fileListLoadedInternal = true
operationInProgress = false
}
for type in StormcloudDocumentType.allTypes() {
guard var hasItems = items[type] else {
continue
}
hasItems.sort { (item1, item2) -> Bool in
return item1.date > item2.date
}
let previousItems : [StormcloudMetadata]
if let hasPreviousItems = internalList[type] {
previousItems = hasPreviousItems
} else {
previousItems = []
}
let deletedItems = previousItems.filter { (metadata) -> Bool in
if hasItems.contains(metadata) {
return false
}
return true
}
var deletedItemsIndices : IndexSet? = IndexSet()
for item in deletedItems {
if let hasIdx = previousItems.firstIndex(of: item) {
deletedItemsIndices?.insert(hasIdx)
stormcloudLog("Item to delete: \(item) at \(hasIdx)")
}
}
let addedItems = hasItems.filter { (url) -> Bool in
if previousItems.contains(url) {
return false
}
return true
}
internalList[type] = hasItems
internalList[type]?.forEach({ (metadata) in
if metadata.iCloudMetadata != nil {
self.delegate?.metadataDidUpdate(metadata, for: type)
}
})
var addedItemsIndices : IndexSet? = IndexSet()
for item in addedItems {
if let didAddItems = internalList[type]!.firstIndex(of: item) {
addedItemsIndices?.insert(didAddItems)
stormcloudLog("Item added at \(didAddItems)")
}
}
addedItemsIndices = (addedItemsIndices?.count == 0) ? nil : addedItemsIndices
deletedItemsIndices = (deletedItemsIndices?.count == 0) ? nil : deletedItemsIndices
self.delegate?.metadataListDidAddItemsAt(addedItemsIndices, andDeletedItemsAt: deletedItemsIndices, for: type)
}
}
}
open class Stormcloud: NSObject {
/// Whether or not the backup manager is currently using iCloud (read only)
open var isUsingiCloud : Bool {
get {
return UserDefaults.standard.bool(forKey: StormcloudPrefKey.isUsingiCloud.rawValue)
}
}
/// The backup manager delegate
open weak var delegate : StormcloudDelegate?
open var coreDataDelegate : StormcloudCoreDataDelegate?
open var shouldDisableInProgressCheck : Bool = false
var fileListLoadedInternal = false {
didSet {
print("Did set")
}
}
open var fileListLoaded : Bool {
get {
return fileListLoadedInternal
}
}
var formatter = DateFormatter()
var workingCache : [String : Any] = [:]
var internalList : [StormcloudDocumentType : [StormcloudMetadata]] = [:]
var operationInProgress : Bool = true
weak var restoreDelegate : StormcloudRestoreDelegate?
var provider : DocumentProvider? {
didSet {
// External references to self will still be nil if the provider is set during initialisation
provider?.delegate = self
// If we've got a new provider, then we need to reset some state
fileListLoadedInternal = false
operationInProgress = true
}
}
init( with provider : DocumentProvider ) {
super.init()
self.provider = provider
// Needs to be set manually. See `provider` property
self.provider?.delegate = self
self.provider?.updateFiles()
// Assume UTC for everything.
self.formatter.timeZone = TimeZone(identifier: "UTC")
}
@objc public override init() {
super.init()
// If iCloud is enabled, start it up and get gathering
if isUsingiCloud, let iCloudProvider = iCloudDocumentProvider() {
self.provider = iCloudProvider
UserDefaults.standard.set(true, forKey: StormcloudPrefKey.isUsingiCloud.rawValue)
} else {
self.provider = LocalDocumentProvider()
UserDefaults.standard.set(false, forKey: StormcloudPrefKey.isUsingiCloud.rawValue)
}
// Needs to be set manually. See `provider` property
self.provider?.delegate = self
self.provider?.updateFiles()
// Assume UTC for everything.
self.formatter.timeZone = TimeZone(identifier: "UTC")
}
/// Returns a list of items for a given type. If the type does not yet exist, sets up the array
///
/// - Parameter type: A registered document type that you're interested in
/// - Returns: An array of metadata objects that represent the files on disk or in iCloud
open func items( for type: StormcloudDocumentType ) -> [StormcloudMetadata] {
if let hasItems = internalList[type] {
return hasItems
} else {
internalList[type] = []
}
return []
}
/**
Enables iCloud
- parameter move: Pass true if you want the manager to attempt to copy any documents in iCloud to local storage
- parameter completion: A completion handler to run when the attempt to copy documents has finished.
*/
open func enableiCloudShouldMoveDocuments( _ move : Bool, completion : ((_ error : StormcloudError?) -> Void)? ) {
let currentItems = self.internalList
deleteAllItems()
if move {
// Handle the moving of documents
self.moveItemsToiCloud(currentItems, completion: completion)
}
}
/**
Disables iCloud in favour of local storage
- parameter move: Pass true if you want the manager to attempt to copy any documents in iCloud to local storage
- parameter completion: A completion handler to run when the attempt to copy documents has finished.
*/
open func disableiCloudShouldMoveiCloudDocumentsToLocal( _ move : Bool, completion : ((_ moveSuccessful : Bool) -> Void)? ) {
let currentItems = self.internalList
deleteAllItems()
if move {
// Handle the moving of documents
self.moveItemsFromiCloud(currentItems, completion: completion)
}
}
func moveItemsToiCloud( _ items : [StormcloudDocumentType : [StormcloudMetadata]], completion : ((_ error : StormcloudError?) -> Void)? ) {
// Our current provider should be an local Document Provider
guard let currentProvider = provider as? LocalDocumentProvider else {
completion?(.iCloudNotEnabled)
return
}
guard let iCloudProvider = iCloudDocumentProvider() else {
// Couldn't start up iCloud
completion?(.iCloudUnavailable)
return
}
provider = iCloudProvider
guard let docsDir = currentProvider.documentsDirectory(), let iCloudDir = iCloudProvider.documentsDirectory() else {
provider = LocalDocumentProvider()
completion?(.iCloudUnavailable)
return
}
UserDefaults.standard.set(true, forKey: StormcloudPrefKey.isUsingiCloud.rawValue)
var allItems = [StormcloudMetadata]()
for type in StormcloudDocumentType.allTypes() {
if let hasItems = items[type] {
allItems.append(contentsOf: hasItems)
}
}
DispatchQueue.global(qos: .default).async {
var hasError : StormcloudError?
for metadata in allItems {
let finalURL = docsDir.appendingPathComponent(metadata.filename)
let finaliCloudURL = iCloudDir.appendingPathComponent(metadata.filename)
do {
try FileManager.default.setUbiquitous(true, itemAt: finalURL, destinationURL: finaliCloudURL)
self.stormcloudLog("Moved item from local \(finalURL) to iCloud: \(finaliCloudURL)")
} catch {
hasError = .couldntMoveDocumentToiCloud
self.stormcloudLog("Error moving item: \(finalURL): \(error.localizedDescription)")
}
}
DispatchQueue.main.async(execute: { () -> Void in
completion?(hasError)
})
}
}
func moveItemsFromiCloud( _ items : [StormcloudDocumentType : [StormcloudMetadata]], completion : ((_ success : Bool ) -> Void)? ) {
// Our current provider should be an iCloud Document Provider
guard let currentProvider = provider as? iCloudDocumentProvider else {
completion?(false)
return
}
// get a reference to a local one
let localProvider = LocalDocumentProvider()
guard let docsDir = localProvider.documentsDirectory(), let iCloudDir = currentProvider.documentsDirectory() else {
completion?(false)
return
}
// Set the provider to our new local provider so it can respond to changes
provider = localProvider
UserDefaults.standard.set(false, forKey: StormcloudPrefKey.isUsingiCloud.rawValue)
var filenames = [String]()
for (_,value) in items {
let allNames = value.map() { $0.filename }
filenames.append(contentsOf: allNames )
}
DispatchQueue.global(qos: .default).async {
var success = true
for element in filenames {
let finalURL = docsDir.appendingPathComponent(element)
let finaliCloudURL = iCloudDir.appendingPathComponent(element)
do {
try FileManager.default.setUbiquitous(false, itemAt: finaliCloudURL, destinationURL: finalURL)
self.stormcloudLog("Moving files from iCloud: \(finaliCloudURL) to local URL: \(finalURL)")
} catch {
self.stormcloudLog("Error moving file: \(finaliCloudURL) from iCloud: \(error.localizedDescription)")
success = false
}
}
DispatchQueue.main.async(execute: { () -> Void in
// self.prepareDocumentList()
completion?(success)
})
}
}
deinit {
print("deinit called")
provider = nil
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - Helper methods
extension Stormcloud {
/**
Gets the URL for a given StormcloudMetadata item. Will return either the local or iCloud URL, but only if it exists
in the internal storage.
- parameter item: The item to get the URL for
- returns: An optional NSURL, giving the location for the item
*/
public func urlForItem(_ item : StormcloudMetadata) -> URL? {
guard let hasItems = internalList[item.type], hasItems.contains(item) else {
return nil
}
return self.provider?.documentsDirectory()?.appendingPathComponent(item.filename)
}
func deleteAllItems() {
for type in StormcloudDocumentType.allTypes() {
if let hasItems = internalList[type] {
let indexesToDelete = IndexSet(0..<hasItems.count)
internalList[type]?.removeAll()
self.delegate?.metadataListDidAddItemsAt(nil, andDeletedItemsAt: indexesToDelete, for: type)
}
}
}
}
// MARK: - Adding Documents
extension Stormcloud {
public func addDocument( withData objects : Any, for documentType : StormcloudDocumentType, completion: @escaping StormcloudDocumentClosure ) {
self.stormcloudLog("\(#function)")
if self.operationInProgress {
completion(.backupInProgress, nil)
return
}
self.operationInProgress = true
// Find out where we should be savindocumentsDirectoryg, based on iCloud or local
guard let baseURL = provider?.documentsDirectory() else {
completion(.invalidURL, nil)
return
}
// Set the file extension to whatever it is we're trying to back up
let metadata : StormcloudMetadata
let document : UIDocument
let finalURL : URL
switch documentType {
case .jpegImage:
metadata = JPEGMetadata()
finalURL = baseURL.appendingPathComponent(metadata.filename)
let imageDocument = ImageDocument(fileURL: finalURL )
if let isImage = objects as? UIImage {
imageDocument.imageToBackup = isImage
}
document = imageDocument
case .json:
metadata = JSONMetadata()
finalURL = baseURL.appendingPathComponent(metadata.filename)
let jsonDocument = JSONDocument(fileURL: finalURL )
jsonDocument.objectsToBackup = objects
document = jsonDocument
default:
metadata = StormcloudMetadata()
finalURL = baseURL.appendingPathComponent(metadata.filename)
document = UIDocument()
}
self.stormcloudLog("Backing up to: \(finalURL)")
let exists : [StormcloudMetadata]
exists = items(for: documentType).filter({ (element) -> Bool in
if element.filename == metadata.filename {
return true
}
return false
})
if exists.count > 0 {
completion(.backupFileExists, nil)
return
}
assert(Thread.current == Thread.main)
document.save(to: finalURL, for: .forCreating, completionHandler: { (success) -> Void in
let totalSuccess = success
if ( !totalSuccess ) {
self.stormcloudLog("\(#function): Error saving new document")
DispatchQueue.main.async(execute: { () -> Void in
self.operationInProgress = false
completion(StormcloudError.couldntSaveNewDocument, nil)
})
return
}
document.close(completionHandler: nil)
DispatchQueue.main.async(execute: { () -> Void in
self.operationInProgress = false
// If we were successful, and it hasn't been added in the meantime, then we can go ahead and append the metadata
if !self.internalList[documentType]!.contains(metadata) {
self.internalList[documentType]?.append(metadata)
self.internalList[documentType]?.sort(by: { (data1, data2) -> Bool in
return data1.date > data2.date
})
if let idx = self.internalList[documentType]?.firstIndex(of: metadata) {
self.delegate?.metadataListDidAddItemsAt(IndexSet(integer: idx), andDeletedItemsAt: nil, for: documentType)
}
}
completion(nil, (totalSuccess) ? metadata : metadata)
})
})
}
}
// MARK: - Restoring
extension Stormcloud {
/**
Restores a JSON object from the given Stormcloud Metadata object
- parameter metadata: The Stormcloud metadata object that represents the document
- parameter completion: A completion handler to run when the operation is completed
*/
public func restoreBackup(from metadata : StormcloudMetadata, completion : @escaping (_ error: StormcloudError?, _ restoredObjects : Any? ) -> () ) {
guard let metadataList = internalList[metadata.type] else {
completion(.invalidDocumentData, nil)
return
}
if metadataList.contains(metadata) {
if let idx = metadataList.firstIndex(of: metadata) {
metadata.iCloudMetadata = metadataList[idx].iCloudMetadata
}
}
if self.operationInProgress && !self.shouldDisableInProgressCheck {
completion(.backupInProgress, nil)
return
}
guard let url = self.urlForItem(metadata) else {
self.operationInProgress = false
completion(.invalidURL, nil)
return
}
if !self.shouldDisableInProgressCheck {
self.operationInProgress = true
}
let document : UIDocument
switch metadata.type {
case .jpegImage:
document = ImageDocument(fileURL: url)
default:
document = JSONDocument(fileURL: url)
}
let _ = document.documentState
document.open(completionHandler: { (success) -> Void in
var error : StormcloudError? = nil
let data : Any?
if let isJSON = document as? JSONDocument, let hasObjects = isJSON.objectsToBackup {
data = hasObjects
} else if let isImage = document as? ImageDocument, let hasImage = isImage.imageToBackup {
data = hasImage
} else {
data = nil
error = StormcloudError.invalidDocumentData
}
if !success {
error = StormcloudError.couldntOpenDocument
}
DispatchQueue.main.async(execute: { () -> Void in
self.operationInProgress = false
self.shouldDisableInProgressCheck = false
completion(error, data)
document.close()
})
})
}
public func deleteItems(_ type : StormcloudDocumentType, overLimit limit : Int, completion : @escaping ( _ error : StormcloudError? ) -> () ) {
// Knock one off as we're about to back up
var itemsToDelete : [StormcloudMetadata] = []
guard let validItems = internalList[type] else {
completion(.invalidDocumentData)
return
}
if limit > 0 && validItems.count > limit {
for i in limit..<validItems.count {
let metadata = validItems[i]
itemsToDelete.append(metadata)
}
}
for item in itemsToDelete {
self.deleteItem(item, completion: { (index, error) -> () in
if let hasError = error {
self.stormcloudLog("Error deleting: \(hasError.localizedDescription)")
completion(.couldntDelete)
} else {
completion(nil)
}
})
}
}
/**
Deletes the document represented by the metadataItem object
- parameter metadataItem: The Stormcloud Metadata object that represents the document
- parameter completion: The completion handler to run when the delete completes
*/
public func deleteItem(_ metadataItem : StormcloudMetadata, completion : @escaping (_ index : Int?, _ error : StormcloudError?) -> () ) {
// Pull them out of the internal list first
guard let itemURL = self.urlForItem(metadataItem), let idx = internalList[metadataItem.type]?.firstIndex(of: metadataItem) else {
completion(nil, .couldntDelete)
return
}
// Remove them from the internal list
DispatchQueue.global(qos: .default).async {
// TESTING ENVIRONMENT
if StormcloudEnvironment.MangleDelete.isEnabled() {
sleep(2)
DispatchQueue.main.async(execute: { () -> Void in
completion(nil, .couldntDelete )
})
return
}
// ENDs
let coordinator = NSFileCoordinator(filePresenter: nil)
coordinator.coordinate(writingItemAt: itemURL, options: .forDeleting, error:nil, byAccessor: { (url) -> Void in
var hasError : NSError?
do {
try FileManager.default.removeItem(at: url)
} catch let error as NSError {
hasError = error
}
if hasError != nil {
completion(nil, .couldntDelete)
} else {
DispatchQueue.main.async {
// If it's still in our internal list at this point, remove it and send the delegate message
if let stillIdx = self.internalList[metadataItem.type]?.firstIndex(of: metadataItem) {
self.internalList[metadataItem.type]!.remove(at: stillIdx)
self.delegate?.metadataListDidAddItemsAt(nil, andDeletedItemsAt: IndexSet(integer: stillIdx), for: metadataItem.type)
}
completion(idx, nil)
}
}
})
}
}
}
extension Stormcloud {
func stormcloudLog( _ string : String ) {
if StormcloudEnvironment.VerboseLogging.isEnabled() {
print(string)
}
}
}
|
c540efb0b7c09dca482c6adc0276e8be
| 28.852025 | 150 | 0.709209 | false | false | false | false |
tuanquanghpvn/ios-swift-tutorial
|
refs/heads/master
|
Tutorial_13_UITableView/Tutorial_13_UITableView/NameTableViewController.swift
|
mit
|
1
|
//
// NameTableViewController.swift
// Tutorial_13_UITableView
//
// Created by on 3/3/16.
// Copyright © 2016 Tuan_Quang. All rights reserved.
//
import UIKit
class NameTableViewController: UITableViewController {
var arrayName: [String]!
override func viewDidLoad() {
super.viewDidLoad()
arrayName = ["Nguyen Van A", "Nguyen Van B", "Nguyen Van C", "Nguyen Van D", "Nguyen Van E", "Nguyen Van F"]
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return arrayName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
cell.textLabel?.text = String(arrayName[indexPath.row])
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
|
629335af0072201f0e29f0578c888278
| 34.649485 | 157 | 0.682765 | false | false | false | false |
CodaFi/swift
|
refs/heads/master
|
test/IDE/complete_type.swift
|
apache-2.0
|
2
|
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
//===--- Helper types that are used in this test
struct FooStruct {
}
var fooObject: FooStruct
func fooFunc() -> FooStruct {
return fooObject
}
enum FooEnum {
}
class FooClass {
}
protocol FooProtocol {
var fooInstanceVar: Int
typealias FooTypeAlias1
func fooInstanceFunc0() -> Double
func fooInstanceFunc1(a: Int) -> Double
subscript(i: Int) -> Double
}
protocol BarProtocol {
var barInstanceVar: Int
typealias BarTypeAlias1
func barInstanceFunc0() -> Double
func barInstanceFunc1(a: Int) -> Double
}
typealias FooTypealias = Int
// WITH_GLOBAL_TYPES: Begin completions
// Global completions
// WITH_GLOBAL_TYPES-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// WITH_GLOBAL_TYPES-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}}
// WITH_GLOBAL_TYPES-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}}
// WITH_GLOBAL_TYPES-DAG: Decl[Protocol]/CurrModule: FooProtocol[#FooProtocol#]{{; name=.+$}}
// WITH_GLOBAL_TYPES-DAG: Decl[TypeAlias]/CurrModule: FooTypealias[#Int#]{{; name=.+$}}
// WITH_GLOBAL_TYPES: End completions
// GLOBAL_NEGATIVE-NOT: fooObject
// GLOBAL_NEGATIVE-NOT: fooFunc
// WITHOUT_GLOBAL_TYPES-NOT: FooStruct
// WITHOUT_GLOBAL_TYPES-NOT: FooEnum
// WITHOUT_GLOBAL_TYPES-NOT: FooClass
// WITHOUT_GLOBAL_TYPES-NOT: FooProtocol
// WITHOUT_GLOBAL_TYPES-NOT: FooTypealias
// ERROR_COMMON: found code completion token
// ERROR_COMMON-NOT: Begin completions
//===---
//===--- Test that we include 'Self' type while completing inside a protocol.
//===---
// TYPE_IN_PROTOCOL: Begin completions
// TYPE_IN_PROTOCOL-DAG: Decl[GenericTypeParam]/Local: Self[#Self#]{{; name=.+$}}
// TYPE_IN_PROTOCOL: End completions
protocol TestSelf1 {
func instanceFunc() -> #^TYPE_IN_PROTOCOL_1?check=TYPE_IN_PROTOCOL;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
//===---
//===--- Test that we include types from generic parameter lists.
//===---
// FIXME: tests for constructors and destructors.
func testTypeInParamGeneric1<
GenericFoo : FooProtocol,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_1?check=TYPE_IN_FUNC_PARAM_GENERIC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
// TYPE_IN_FUNC_PARAM_GENERIC_1: Begin completions
// Generic parameters of the function.
// TYPE_IN_FUNC_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_1: End completions
struct TestTypeInParamGeneric2<
StructGenericFoo : FooProtocol,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
func testTypeInParamGeneric2(a: #^TYPE_IN_FUNC_PARAM_GENERIC_2?check=TYPE_IN_FUNC_PARAM_GENERIC_2;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_FUNC_PARAM_GENERIC_2: Begin completions
// TYPE_IN_FUNC_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_2: End completions
struct TestTypeInParamGeneric3 {
func testTypeInParamGeneric3<
GenericFoo : FooProtocol,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_3?check=TYPE_IN_FUNC_PARAM_GENERIC_3;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_FUNC_PARAM_GENERIC_3: Begin completions
// TYPE_IN_FUNC_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_3: End completions
struct TestTypeInParamGeneric4<
StructGenericFoo : FooProtocol,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
func testTypeInParamGeneric4<
GenericFoo : FooProtocol,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_4?check=TYPE_IN_FUNC_PARAM_GENERIC_4;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_FUNC_PARAM_GENERIC_4: Begin completions
// Generic parameters of the struct.
// TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}}
// Generic parameters of the function.
// TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_4-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_4: End completions
struct TestTypeInParamGeneric5<StructGenericFoo> {
struct TestTypeInParamGeneric5a<StructGenericBar> {
struct TestTypeInParamGeneric5b<StructGenericBaz> {
func testTypeInParamGeneric5<GenericFoo>(a: #^TYPE_IN_FUNC_PARAM_GENERIC_5?check=TYPE_IN_FUNC_PARAM_GENERIC_5;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
}
}
// TYPE_IN_FUNC_PARAM_GENERIC_5: Begin completions
// Generic parameters of the containing structs.
// TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}}
// Generic parameters of the function.
// TYPE_IN_FUNC_PARAM_GENERIC_5-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// TYPE_IN_FUNC_PARAM_GENERIC_5: End completions
struct TestTypeInConstructorParamGeneric1<
StructGenericFoo : FooProtocol,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
init(a: #^TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1?check=TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1: Begin completions
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_1: End completions
struct TestTypeInConstructorParamGeneric2 {
init<GenericFoo : FooProtocol,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: #^TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2?check=TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2: Begin completions
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_2: End completions
struct TestTypeInConstructorParamGeneric3<
StructGenericFoo : FooProtocol,
StructGenericBar : FooProtocol & BarProtocol,
StructGenericBaz> {
init<GenericFoo : FooProtocol,
GenericBar : FooProtocol & BarProtocol,
GenericBaz>(a: #^TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3?check=TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3: Begin completions
// Generic parameters of the struct.
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: StructGenericFoo[#StructGenericFoo#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: StructGenericBar[#StructGenericBar#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: StructGenericBaz[#StructGenericBaz#]{{; name=.+$}}
// Generic parameters of the constructor.
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericFoo[#GenericFoo#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBar[#GenericBar#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3-DAG: Decl[GenericTypeParam]/Local: GenericBaz[#GenericBaz#]{{; name=.+$}}
// TYPE_IN_CONSTRUCTOR_PARAM_GENERIC_3: End completions
// No tests for destructors: destructors don't have parameters.
//===---
//===--- Test that we don't duplicate generic parameters.
//===---
struct GenericStruct<T> {
func foo() -> #^TYPE_IN_RETURN_GEN_PARAM_NO_DUP^#
}
class A<T> {
var foo: #^TYPE_IVAR_GEN_PARAM_NO_DUP^#
subscript(_ arg: Int) -> #^TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP^#
}
// TYPE_IN_RETURN_GEN_PARAM_NO_DUP: Begin completions
// TYPE_IN_RETURN_GEN_PARAM_NO_DUP-DAG: Decl[GenericTypeParam]/Local: T[#T#]; name=T
// TYPE_IN_RETURN_GEN_PARAM_NO_DUP-NOT: Decl[GenericTypeParam]/Local: T[#T#]; name=T
// TYPE_IN_RETURN_GEN_PARAM_NO_DUP: End completions
// TYPE_IVAR_GEN_PARAM_NO_DUP: Begin completions
// TYPE_IVAR_GEN_PARAM_NO_DUP-DAG: Decl[GenericTypeParam]/Local: T[#T#]; name=T
// TYPE_IVAR_GEN_PARAM_NO_DUP-NOT: Decl[GenericTypeParam]/Local: T[#T#]; name=T
// TYPE_IVAR_GEN_PARAM_NO_DUP: End completions
// TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP: Begin completions
// TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP-DAG: Decl[GenericTypeParam]/Local: T[#T#]; name=T
// TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP-NOT: Decl[GenericTypeParam]/Local: T[#T#]; name=T
// TYPE_IN_SUBSCR_GEN_PARAM_NO_DUP: End completions
//===---
//===--- Test that we can complete types in variable declarations.
//===---
func testTypeInLocalVarInFreeFunc1() {
var localVar: #^TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInLocalVarInFreeFunc2() {
struct NestedStruct {}
class NestedClass {}
enum NestedEnum {
case NestedEnumX(Int)
}
typealias NestedTypealias = Int
var localVar: #^TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2?check=TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2: Begin completions
// TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[Struct]/Local: NestedStruct[#NestedStruct#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[Class]/Local: NestedClass[#NestedClass#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[Enum]/Local: NestedEnum[#NestedEnum#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2-DAG: Decl[TypeAlias]/Local: NestedTypealias[#Int#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_FREE_FUNC_2: End completions
class TestTypeInLocalVarInMemberFunc1 {
struct NestedStruct {}
class NestedClass {}
enum NestedEnum {
case NestedEnumX(Int)
}
typealias NestedTypealias = Int
init() {
var localVar: #^TYPE_IN_LOCAL_VAR_IN_CONSTRUCTOR_1?check=TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
deinit {
var localVar: #^TYPE_IN_LOCAL_VAR_IN_DESTRUCTOR_1?check=TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func test() {
var localVar: #^TYPE_IN_LOCAL_VAR_IN_INSTANCE_FUNC_1?check=TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
}
// TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1: Begin completions
// TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[Struct]/CurrNominal: NestedStruct[#NestedStruct#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[Class]/CurrNominal: NestedClass[#NestedClass#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[Enum]/CurrNominal: NestedEnum[#NestedEnum#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1-DAG: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}}
// TYPE_IN_LOCAL_VAR_IN_MEMBER_FUNC_1: End completions
var TypeInGlobalVar1: #^TYPE_IN_GLOBAL_VAR_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
//===---
//===--- Test that we can complete types in typealias declarations.
//===---
typealias TypeInTypealias1 = #^TYPE_IN_TYPEALIAS_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
typealias TypeInTypealias2 = (#^TYPE_IN_TYPEALIAS_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func resyncParser0() {}
typealias TypeInTypealias3 = ((#^TYPE_IN_TYPEALIAS_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func resyncParser1() {}
//===---
//===--- Test that we can complete types in associated type declarations.
//===---
protocol AssocType1 {
associatedtype AssocType = #^TYPE_IN_ASSOC_TYPE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
//===---
//===--- Test that we can complete types in inheritance clause of associated type declarations.
//===---
protocol AssocType1 {
associatedtype AssocType : #^TYPE_IN_ASSOC_TYPE_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
//===---
//===--- Test that we can complete types in extension declarations.
//===---
extension #^TYPE_IN_EXTENSION_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
//===---
//===--- Test that we can complete types in the extension inheritance clause.
//===---
extension TypeInExtensionInheritance1 : #^TYPE_IN_EXTENSION_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
extension TypeInExtensionInheritance2 : #^TYPE_IN_EXTENSION_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
extension TypeInExtensionInheritance3 : FooProtocol, #^TYPE_IN_EXTENSION_INHERITANCE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
//===---
//===--- Test that we can complete types in the struct inheritance clause.
//===---
struct TypeInStructInheritance1 : #^TYPE_IN_STRUCT_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
struct TypeInStructInheritance2 : , #^TYPE_IN_STRUCT_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
struct TypeInStructInheritance3 : FooProtocol, #^TYPE_IN_STRUCT_INHERITANCE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
struct TypeInStructInheritance4 : FooProtocol., #^TYPE_IN_STRUCT_INHERITANCE_4?check=WITH_GLOBAL_TYPES^#
struct TypeInStructInheritance5 : #^TYPE_IN_STRUCT_INHERITANCE_5?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
struct TypeInStructInheritance6 : , #^TYPE_IN_STRUCT_INHERITANCE_6?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
struct TypeInStructInheritance7 : FooProtocol, #^TYPE_IN_STRUCT_INHERITANCE_7?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
struct TypeInStructInheritance8 : FooProtocol., #^TYPE_IN_STRUCT_INHERITANCE_8?check=WITH_GLOBAL_TYPES^# {
}
//===---
//===--- Test that we can complete types in the class inheritance clause.
//===---
class TypeInClassInheritance1 : #^TYPE_IN_CLASS_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
class TypeInClassInheritance2 : #^TYPE_IN_CLASS_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
//===---
//===--- Test that we can complete types in the enum inheritance clause.
//===---
enum TypeInEnumInheritance1 : #^TYPE_IN_ENUM_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
enum TypeInEnumInheritance2 : #^TYPE_IN_ENUM_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
//===---
//===--- Test that we can complete types in the protocol inheritance clause.
//===---
protocol TypeInProtocolInheritance1 : #^TYPE_IN_PROTOCOL_INHERITANCE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
protocol TypeInProtocolInheritance2 : #^TYPE_IN_PROTOCOL_INHERITANCE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# {
}
//===---
//===--- Test that we can complete types in tuple types.
//===---
func testTypeInTupleType1() {
var localVar: (#^TYPE_IN_TUPLE_TYPE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInTupleType2() {
var localVar: (a: #^TYPE_IN_TUPLE_TYPE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInTupleType3() {
var localVar: (Int, #^TYPE_IN_TUPLE_TYPE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInTupleType4() {
var localVar: (a: Int, #^TYPE_IN_TUPLE_TYPE_4?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInTupleType5() {
var localVar: (Int, a: #^TYPE_IN_TUPLE_TYPE_5?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInTupleType6() {
var localVar: (a:, #^TYPE_IN_TUPLE_TYPE_6?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInTupleType7() {
var localVar: (a: b: #^TYPE_IN_TUPLE_TYPE_7?skip=FIXME^#
}
//===---
//===--- Test that we can complete types in function types.
//===---
func testTypeInFunctionType1() {
var localVar: #^TYPE_IN_FUNCTION_TYPE_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^# ->
}
func testTypeInFunctionType2() {
var localVar: (#^TYPE_IN_FUNCTION_TYPE_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#) -> ()
}
func testTypeInFunctionType3() {
var localVar: () -> #^TYPE_IN_FUNCTION_TYPE_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInFunctionType4() {
var localVar: (Int) -> #^TYPE_IN_FUNCTION_TYPE_4?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInFunctionType5() {
var localVar: (a: Int) -> #^TYPE_IN_FUNCTION_TYPE_5?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInFunctionType6() {
var localVar: (a: Int, ) -> #^TYPE_IN_FUNCTION_TYPE_6?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
//===---
//===--- Test that we can complete types in protocol compositions.
//===---
func testTypeInProtocolComposition1() {
var localVar: protocol<#^TYPE_IN_PROTOCOL_COMPOSITION_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInProtocolComposition2() {
var localVar: protocol<, #^TYPE_IN_PROTOCOL_COMPOSITION_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
func testTypeInProtocolComposition3() {
var localVar: protocol<FooProtocol, #^TYPE_IN_PROTOCOL_COMPOSITION_3?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
//===---
//===--- Test that we can complete types from extensions and base classes.
//===---
class VarBase1 {
var instanceVarBase1: #^TYPE_IN_INSTANCE_VAR_1?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func paramNestedTypesBase1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_1?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func localVarBaseTest1() {
var localVar: #^TYPE_IN_LOCAL_VAR_1?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// Define types after all tests to test delayed parsing of decls.
struct BaseNestedStruct {}
class BaseNestedClass {}
enum BaseNestedEnum {
case BaseEnumX(Int)
}
typealias BaseNestedTypealias = Int
}
extension VarBase1 {
var instanceVarBaseExt1: #^TYPE_IN_INSTANCE_VAR_2?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func paramNestedTypesBaseExt1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_2?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func localVarBaseExtTest1() {
var localVar: #^TYPE_IN_LOCAL_VAR_2?check=VAR_BASE_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// Define types after all tests to test delayed parsing of decls.
struct BaseExtNestedStruct {}
class BaseExtNestedClass {}
enum BaseExtNestedEnum {
case BaseExtEnumX(Int)
}
typealias BaseExtNestedTypealias = Int
}
// VAR_BASE_1_TYPES: Begin completions
// From VarBase1
// VAR_BASE_1_TYPES-DAG: Decl[Struct]/CurrNominal: BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}}
// VAR_BASE_1_TYPES-DAG: Decl[Class]/CurrNominal: BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}}
// VAR_BASE_1_TYPES-DAG: Decl[Enum]/CurrNominal: BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}}
// VAR_BASE_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: BaseNestedTypealias[#Int#]{{; name=.+$}}
// From VarBase1 extension
// VAR_BASE_1_TYPES-DAG: Decl[Struct]/CurrNominal: BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}}
// VAR_BASE_1_TYPES-DAG: Decl[Class]/CurrNominal: BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}}
// VAR_BASE_1_TYPES-DAG: Decl[Enum]/CurrNominal: BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}}
// VAR_BASE_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: BaseExtNestedTypealias[#Int#]{{; name=.+$}}
// VAR_BASE_1_TYPES: End completions
// VAR_BASE_1_TYPES_INCONTEXT: Begin completions
// From VarBase1
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: BaseNestedStruct[#BaseNestedStruct#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: BaseNestedClass[#BaseNestedClass#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: BaseNestedEnum[#BaseNestedEnum#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: BaseNestedTypealias[#Int#]{{; name=.+$}}
// From VarBase1 extension
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: BaseExtNestedStruct[#BaseExtNestedStruct#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: BaseExtNestedClass[#BaseExtNestedClass#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: BaseExtNestedEnum[#BaseExtNestedEnum#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: BaseExtNestedTypealias[#Int#]{{; name=.+$}}
// VAR_BASE_1_TYPES_INCONTEXT: End completions
// VAR_BASE_1_NO_DOT_TYPES: Begin completions
// From VarBase1
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Struct]/CurrNominal: .BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Class]/CurrNominal: .BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Enum]/CurrNominal: .BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BaseNestedTypealias[#Int#]{{; name=.+$}}
// From VarBase1 extension
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Struct]/CurrNominal: .BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Class]/CurrNominal: .BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[Enum]/CurrNominal: .BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES-DAG: Decl[TypeAlias]/CurrNominal: .BaseExtNestedTypealias[#Int#]{{; name=.+$}}
// VAR_BASE_1_NO_DOT_TYPES: End completions
class VarDerived1 : VarBase1 {
var instanceVarDerived1 : #^TYPE_IN_INSTANCE_VAR_3?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func paramNestedTypesDerived1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_3?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func localVarDerivedTest1() {
var localVar : #^TYPE_IN_LOCAL_VAR_3?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// Define types after all tests to test delayed parsing of decls.
struct DerivedNestedStruct {}
class DerivedNestedClass {}
enum DerivedNestedEnum {
case DerivedEnumX(Int)
}
typealias DerivedNestedTypealias = Int
}
extension VarDerived1 {
var instanceVarDerivedExt1 : #^TYPE_IN_INSTANCE_VAR_4?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func paramNestedTypesDerivedExt1(a: #^TYPE_IN_FUNC_PARAM_NESTED_TYPES_4?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func localVarDerivedExtTest1() {
var localVar : #^TYPE_IN_LOCAL_VAR_4?check=VAR_DERIVED_1_TYPES_INCONTEXT;check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
// Define types after all tests to test delayed parsing of decls.
struct DerivedExtNestedStruct {}
class DerivedExtNestedClass {}
enum DerivedExtNestedEnum {
case DerivedExtEnumX(Int)
}
typealias DerivedExtNestedTypealias = Int
}
// VAR_DERIVED_1_TYPES: Begin completions
// From VarBase1
// VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/Super: BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Class]/Super: BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/Super: BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/Super: BaseNestedTypealias[#Int#]{{; name=.+$}}
// From VarBase1 extension
// VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/Super: BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Class]/Super: BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/Super: BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/Super: BaseExtNestedTypealias[#Int#]{{; name=.+$}}
// From VarDerived1
// VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/CurrNominal: DerivedNestedStruct[#VarDerived1.DerivedNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Class]/CurrNominal: DerivedNestedClass[#VarDerived1.DerivedNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/CurrNominal: DerivedNestedEnum[#VarDerived1.DerivedNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: DerivedNestedTypealias[#Int#]{{; name=.+$}}
// From VarDerived1 extension
// VAR_DERIVED_1_TYPES-DAG: Decl[Struct]/CurrNominal: DerivedExtNestedStruct[#VarDerived1.DerivedExtNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Class]/CurrNominal: DerivedExtNestedClass[#VarDerived1.DerivedExtNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[Enum]/CurrNominal: DerivedExtNestedEnum[#VarDerived1.DerivedExtNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES-DAG: Decl[TypeAlias]/CurrNominal: DerivedExtNestedTypealias[#Int#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES: End completions
// VAR_DERIVED_1_TYPES_INCONTEXT: Begin completions
// From VarBase1
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/Super: BaseNestedStruct[#VarBase1.BaseNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/Super: BaseNestedClass[#VarBase1.BaseNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/Super: BaseNestedEnum[#VarBase1.BaseNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/Super: BaseNestedTypealias[#Int#]{{; name=.+$}}
// From VarBase1 extension
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/Super: BaseExtNestedStruct[#VarBase1.BaseExtNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/Super: BaseExtNestedClass[#VarBase1.BaseExtNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/Super: BaseExtNestedEnum[#VarBase1.BaseExtNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/Super: BaseExtNestedTypealias[#Int#]{{; name=.+$}}
// From VarDerived1
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: DerivedNestedStruct[#DerivedNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: DerivedNestedClass[#DerivedNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: DerivedNestedEnum[#DerivedNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: DerivedNestedTypealias[#Int#]{{; name=.+$}}
// From VarDerived1 extension
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Struct]/CurrNominal: DerivedExtNestedStruct[#DerivedExtNestedStruct#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Class]/CurrNominal: DerivedExtNestedClass[#DerivedExtNestedClass#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[Enum]/CurrNominal: DerivedExtNestedEnum[#DerivedExtNestedEnum#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT-DAG: Decl[TypeAlias]/CurrNominal: DerivedExtNestedTypealias[#Int#]{{; name=.+$}}
// VAR_DERIVED_1_TYPES_INCONTEXT: End completions
//===---
//===--- Test that we can complete based on user-provided type-identifier.
//===---
func testTypeIdentifierBase1(a: VarBase1.#^TYPE_IDENTIFIER_BASE_1?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierBase2(a: Int, b: VarBase1.#^TYPE_IDENTIFIER_BASE_2?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierBase3(a: unknown_type, b: VarBase1.#^TYPE_IDENTIFIER_BASE_3?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierBase4(a: , b: VarBase1.#^TYPE_IDENTIFIER_BASE_4?check=VAR_BASE_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierBaseNoDot1(a: VarBase1#^TYPE_IDENTIFIER_BASE_NO_DOT_1?check=VAR_BASE_1_NO_DOT_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierBaseNoDot2() {
var localVar : protocol<VarBase1#^TYPE_IDENTIFIER_BASE_NO_DOT_2?check=VAR_BASE_1_NO_DOT_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
typealias testTypeIdentifierBaseNoDot3 = VarBase1#^TYPE_IDENTIFIER_BASE_NO_DOT_3?check=VAR_BASE_1_NO_DOT_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierDerived1(a: VarDerived1.#^TYPE_IDENTIFIER_DERIVED_1?check=VAR_DERIVED_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierDerived2() {
var localVar : protocol<VarDerived1.#^TYPE_IDENTIFIER_DERIVED_2?check=VAR_DERIVED_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
typealias testTypeIdentifierDerived3 = VarDerived1.#^TYPE_IDENTIFIER_DERIVED_3?check=VAR_DERIVED_1_TYPES;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
func testTypeIdentifierGeneric1<
GenericFoo : FooProtocol
>(a: GenericFoo.#^TYPE_IDENTIFIER_GENERIC_1?check=TYPE_IDENTIFIER_GENERIC_1;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
// TYPE_IDENTIFIER_GENERIC_1: Begin completions
// TYPE_IDENTIFIER_GENERIC_1-NEXT: Decl[AssociatedType]/CurrNominal: FooTypeAlias1{{; name=.+$}}
// TYPE_IDENTIFIER_GENERIC_1-NEXT: Keyword/None: Type[#GenericFoo.Type#]
// TYPE_IDENTIFIER_GENERIC_1-NEXT: End completions
func testTypeIdentifierGeneric2<
GenericFoo : FooProtocol & BarProtocol
>(a: GenericFoo.#^TYPE_IDENTIFIER_GENERIC_2?check=TYPE_IDENTIFIER_GENERIC_2;check=WITHOUT_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
// TYPE_IDENTIFIER_GENERIC_2: Begin completions
// TYPE_IDENTIFIER_GENERIC_2-NEXT: Decl[AssociatedType]/CurrNominal: BarTypeAlias1{{; name=.+$}}
// TYPE_IDENTIFIER_GENERIC_2-NEXT: Decl[AssociatedType]/CurrNominal: FooTypeAlias1{{; name=.+$}}
// TYPE_IDENTIFIER_GENERIC_2-NEXT: Keyword/None: Type[#GenericFoo.Type#]
// TYPE_IDENTIFIER_GENERIC_2-NEXT: End completions
func testTypeIdentifierGeneric3<
GenericFoo>(a: GenericFoo.#^TYPE_IDENTIFIER_GENERIC_3^#
// TYPE_IDENTIFIER_GENERIC_3: Begin completions
// TYPE_IDENTIFIER_GENERIC_3-NEXT: Keyword/None: Type[#GenericFoo.Type#]
// TYPE_IDENTIFIER_GENERIC_3-NOT: Keyword/CurrNominal: self[#GenericFoo#]
// TYPE_IDENTIFIER_GENERIC_3-NEXT: End completions
func testTypeIdentifierIrrelevant1() {
var a: Int
#^TYPE_IDENTIFIER_IRRELEVANT_1^#
}
// TYPE_IDENTIFIER_IRRELEVANT_1: Begin completions
// TYPE_IDENTIFIER_IRRELEVANT_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// TYPE_IDENTIFIER_IRRELEVANT_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// TYPE_IDENTIFIER_IRRELEVANT_1: End completions
//===---
//===--- Test that we can complete types in 'as' cast.
//===---
func testAsCast1(a: Int) {
a as #^INSIDE_AS_CAST_1?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#
}
//===---
//===--- Test that we can complete generic typealiases.
//===---
func testGenericTypealias1() {
typealias MyPair<T> = (T, T)
let x: #^GENERIC_TYPEALIAS_1^#
}
// FIXME: should we use the alias name in the annotation?
// GENERIC_TYPEALIAS_1: Decl[TypeAlias]/Local: MyPair[#(T, T)#];
func testGenericTypealias2() {
typealias MyPair<T> = (T, T)
let x: MyPair<#^GENERIC_TYPEALIAS_2?check=WITH_GLOBAL_TYPES;check=GLOBAL_NEGATIVE^#>
}
// In generic argument
struct GenStruct<T> { }
let a : GenStruct<#^GENERIC_ARGS_TOPLEVEL_VAR?check=WITH_GLOBAL_TYPES^#
func foo1(x: GenStruct<#^GENERIC_ARGS_TOPLEVEL_PARAM?check=WITH_GLOBAL_TYPES^#
func foo2() -> GenStruct<#^GENERIC_ARGS_TOPLEVEL_RETURN?check=WITH_GLOBAL_TYPES^#
class _TestForGenericArg_ {
let a : GenStruct<#^GENERIC_ARGS_MEMBER_VAR?check=WITH_GLOBAL_TYPES^#
func foo1(x: GenStruct<#^GENERIC_ARGS_MEMBER_PARAM?check=WITH_GLOBAL_TYPES^#
func foo2() -> GenStruct<#^GENERIC_ARGS_MEMBER_RETURN?check=WITH_GLOBAL_TYPES^#
}
func _testForGenericArg_() {
let a : GenStruct<#^GENERIC_ARGS_LOCAL_VAR?check=WITH_GLOBAL_TYPES^#
func foo1(x: GenStruct<#^GENERIC_ARGS_LOCAL_PARAM?check=WITH_GLOBAL_TYPES^#
func foo2() -> GenStruct<#^GENERIC_ARGS_LOCAL_RETURN?check=WITH_GLOBAL_TYPES^#
}
func testProtocol() {
let _: FooProtocol.#^PROTOCOL_DOT_1^#
// PROTOCOL_DOT_1: Begin completions, 3 items
// PROTOCOL_DOT_1-DAG: Decl[AssociatedType]/CurrNominal: FooTypeAlias1; name=FooTypeAlias1
// PROTOCOL_DOT_1-DAG: Keyword/None: Protocol[#FooProtocol.Protocol#]; name=Protocol
// PROTOCOL_DOT_1-DAG: Keyword/None: Type[#FooProtocol.Type#]; name=Type
// PROTOCOL_DOT_1: End completions
}
//===---
//===--- Test we can complete unbound generic types
//===---
public final class Task<Success> {
public enum Inner {
public typealias Failure = Int
case success(Success)
case failure(Failure)
}
}
extension Task.Inner {
public init(left error: Failure) {
fatalError()
}
}
extension Task.Inner.#^UNBOUND_DOT_1?check=UNBOUND_DOT^# {}
func testUnbound(x: Task.Inner.#^UNBOUND_DOT_2?check=UNBOUND_DOT^#) {}
// UNBOUND_DOT: Begin completions
// UNBOUND_DOT-DAG: Decl[TypeAlias]/CurrNominal: Failure[#Int#]; name=Failure
// UNBOUND_DOT-DAG: Keyword/None: Type[#Task.Inner.Type#]; name=Type
// UNBOUND_DOT: End completions
protocol MyProtocol {}
struct OuterStruct<U> {
class Inner<V>: MyProtocol {}
}
func testUnbound2(x: OuterStruct<Int>.Inner.#^UNBOUND_DOT_3^#) {}
// UNBOUND_DOT_3: Begin completions
// UNBOUND_DOT_3-DAG: Keyword/None: Type[#OuterStruct<Int>.Inner.Type#]; name=Type
// UNBOUND_DOT_3: End completions
// rdar://problem/67102794
struct HasProtoAlias {
typealias ProtoAlias = FooProtocol
}
extension FooStruct: HasProtoAlias.#^EXTENSION_INHERITANCE_1?check=EXTENSION_INHERITANCE^# {}
struct ContainExtension {
extension FooStruct: HasProtoAlias.#^EXTENSION_INHERITANCE_2?check=EXTENSION_INHERITANCE^# {}
}
// EXTENSION_INHERITANCE: Begin completions, 2 items
// EXTENSION_INHERITANCE-DAG: Decl[TypeAlias]/CurrNominal: ProtoAlias[#FooProtocol#];
// EXTENSION_INHERITANCE-DAG: Keyword/None: Type[#HasProtoAlias.Type#];
// EXTENSION_INHERITANCE: End completions
|
4796b94201cf450f7c41c0760356562e
| 45.053777 | 163 | 0.727897 | false | true | false | false |
SlackKit/SlackKit
|
refs/heads/main
|
SKCore/Sources/Team.swift
|
mit
|
2
|
//
// Team.swift
//
// Copyright © 2017 Peter Zignego. 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.
public struct Team {
public let id: String?
public var name: String?
public var domain: String?
public var emailDomain: String?
public var messageEditWindowMinutes: Int?
public var overStorageLimit: Bool?
public var prefs: [String: Any]?
public var plan: String?
public var icon: TeamIcon?
public init(team: [String: Any]?) {
id = team?["id"] as? String
name = team?["name"] as? String
domain = team?["domain"] as? String
emailDomain = team?["email_domain"] as? String
messageEditWindowMinutes = team?["msg_edit_window_mins"] as? Int
overStorageLimit = team?["over_storage_limit"] as? Bool
prefs = team?["prefs"] as? [String: Any]
plan = team?["plan"] as? String
icon = TeamIcon(icon: team?["icon"] as? [String: Any])
}
}
|
a028fb6912392f7332ff7d5c1e3a6d8f
| 42.282609 | 80 | 0.699648 | false | false | false | false |
s-emp/TinkoffChat
|
refs/heads/master
|
TinkoffChat/TinkoffChat/Modules/Profile/CoreLayout/Locale/OperationDataManager.swift
|
mit
|
1
|
//
// OperationDataManager.swift
// TinkoffChat
//
// Created by Sergey on 31.10.17.
// Copyright © 2017 Сергей Мельников. All rights reserved.
//
import Foundation
fileprivate class OperationSaveUser: Operation {
var user: User!
var fileName: String = "user.txt"
var callback: ((Bool) -> Void)!
private func checkDirectory() -> URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
}
override func main() {
guard let path = self.checkDirectory() else { return }
do {
let jsonUser = try JSONEncoder().encode(user)
try jsonUser.write(to: path.appendingPathComponent(self.fileName))
callback(true)
} catch {
print("could't create file text.txt because of error: \(error.localizedDescription)")
callback(false)
}
}
}
fileprivate class OperationLoadUser: Operation {
var fileName: String!
var callback: ((User?) -> Void)!
private func checkDirectory() -> URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
}
override func main() {
guard let path = self.checkDirectory() else {
callback(nil)
return
}
do {
let data = try Data(contentsOf: path.appendingPathComponent(self.fileName))
callback(try JSONDecoder().decode(User.self, from: data))
return
} catch {
print(error.localizedDescription)
callback(nil)
return
}
}
}
class OperationDataManager: DataManager {
let queue = OperationQueue()
private var fileName: String!
func prepareObject(fileName: String) {
self.fileName = fileName
}
func saveUser(_ user: User, callback: @escaping (Bool) -> Void) {
let saveUserOperation = OperationSaveUser()
saveUserOperation.callback = callback
saveUserOperation.user = user
saveUserOperation.fileName = fileName
queue.addOperation(saveUserOperation)
}
func loadUser(callback: @escaping (User?) -> Void) {
let loadUserOperation = OperationLoadUser()
loadUserOperation.callback = callback
loadUserOperation.fileName = fileName
queue.addOperation(loadUserOperation)
}
}
|
1f304f57a6ef64dd63691f06f87da98c
| 27.035714 | 97 | 0.628025 | false | false | false | false |
cdmx/MiniMancera
|
refs/heads/master
|
miniMancera/Model/Option/WhistlesVsZombies/Whistle/Type/MOptionWhistlesVsZombiesWhistleTypeOrange.swift
|
mit
|
1
|
import UIKit
class MOptionWhistlesVsZombiesWhistleTypeOrange:MOptionWhistlesVsZombiesWhistleTypeProtocol
{
private(set) var whistle:MOptionWhistlesVsZombiesWhistleProtocol
private(set) var boardItemType:MOptionWhistlesVsZombiesBoardItemProtocol.Type
private(set) var texture:MGameTexture
private(set) var colour:UIColor
private(set) var barrelLength:CGFloat
private let kBarrelLength:CGFloat = 18
init(textures:MOptionWhistlesVsZombiesTextures)
{
whistle = MOptionWhistlesVsZombiesWhistleOrange()
boardItemType = MOptionWhistlesVsZombiesBoardItemOrange.self
texture = textures.whistleOrange
colour = UIColor(
red:0.96078431372549,
green:0.650980392156863,
blue:0.137254901960784,
alpha:1)
barrelLength = kBarrelLength
}
}
|
dfae902fd13b11a40cdca10364ab0c37
| 34.5 | 91 | 0.735915 | false | false | false | false |
omise/omise-ios
|
refs/heads/master
|
OmiseSDK/InstallmentBankingSourceChooserViewController.swift
|
mit
|
1
|
import UIKit
import os
@objc(OMSInstallmentBankingSourceChooserViewController)
// swiftlint:disable:next type_name
class InstallmentBankingSourceChooserViewController: AdaptableStaticTableViewController<PaymentInformation.Installment.Brand>,
PaymentSourceChooser,
PaymentChooserUI {
var flowSession: PaymentCreatorFlowSession?
override var showingValues: [PaymentInformation.Installment.Brand] {
didSet {
os_log("Installment Brand Chooser: Showing options - %{private}@",
log: uiLogObject,
type: .info,
showingValues.map { $0.description }.joined(separator: ", "))
}
}
@IBOutlet var bankNameLabels: [UILabel]!
@IBInspectable var preferredPrimaryColor: UIColor? {
didSet {
applyPrimaryColor()
}
}
@IBInspectable var preferredSecondaryColor: UIColor? {
didSet {
applySecondaryColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
applyPrimaryColor()
applySecondaryColor()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
override func staticIndexPath(forValue value: PaymentInformation.Installment.Brand) -> IndexPath {
switch value {
case .bbl:
return IndexPath(row: 0, section: 0)
case .kBank:
return IndexPath(row: 1, section: 0)
case .bay:
return IndexPath(row: 2, section: 0)
case .firstChoice:
return IndexPath(row: 3, section: 0)
case .ktc:
return IndexPath(row: 4, section: 0)
case .mbb:
return IndexPath(row: 5, section: 0)
case .scb:
return IndexPath(row: 6, section: 0)
case .citi:
return IndexPath(row: 7, section: 0)
case .ttb:
return IndexPath(row: 8, section: 0)
case .uob:
return IndexPath(row: 9, section: 0)
case .other:
preconditionFailure("This value is not supported for built-in chooser")
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let cell = cell as? PaymentOptionTableViewCell {
cell.separatorView.backgroundColor = currentSecondaryColor
}
cell.accessoryView?.tintColor = currentSecondaryColor
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
let selectedBrand = element(forUIIndexPath: indexPath)
os_log("Installment Brand Chooser: %{private}@ was selected", log: uiLogObject, type: .info, selectedBrand.description)
performSegue(withIdentifier: "GoToInstallmentTermsChooserSegue", sender: cell)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) else {
return
}
let selectedBrand = element(forUIIndexPath: indexPath)
if segue.identifier == "GoToInstallmentTermsChooserSegue",
let installmentTermsChooserViewController = segue.destination as? InstallmentsNumberOfTermsChooserViewController {
installmentTermsChooserViewController.installmentBrand = selectedBrand
installmentTermsChooserViewController.flowSession = self.flowSession
installmentTermsChooserViewController.preferredPrimaryColor = self.preferredPrimaryColor
installmentTermsChooserViewController.preferredSecondaryColor = self.preferredSecondaryColor
}
}
private func applyPrimaryColor() {
guard isViewLoaded else {
return
}
bankNameLabels.forEach {
$0.textColor = currentPrimaryColor
}
}
private func applySecondaryColor() {
}
}
|
f0179d55f8dbaca85e9f8a954492d40f
| 36.513043 | 127 | 0.624478 | false | false | false | false |
kadarandras/KAAuthenticationManager
|
refs/heads/master
|
KAAuthenticationManager.swift
|
mit
|
1
|
//
// AuthenticationManager.swift
// cfo
//
// Created by Andras Kadar on 2015. 10. 28..
// Copyright (c) 2015. Inceptech. All rights reserved.
//
import UIKit
public protocol KAAuthenticationManagerDelegate: class {
func showLogin()
func showLicence()
func serverLogin(email: String, password: String, loginCompletionHandler: (KAAuthenticationManager.LoginResult -> Void))
func forgotPassword(email: String, forgotCompletionHandler: (() -> Void))
}
public extension KAAuthenticationManagerDelegate where Self: UIViewController {
func showLogin() {
KAAuthenticationManager.sharedInstance.showLogin(fromViewController: self)
}
}
public extension KAAuthenticationManagerDelegate {
func showLicence() {
}
func forgotPassword(email: String, forgotCompletionHandler: (() -> Void)) {
}
}
public class KAAuthenticationManager: NSObject {
public enum LoginResult {
case IncorrectFormatNoPassword
case IncorrectFormatTooShortPassword
case IncorrectFormatWrongEmailFormat
case NoInternetConnection
case ServerNotReachable
case WrongCredentials
case UnknownError(errorMessage: String?)
case SuccessfulLogin
static var formatErrorTypes: [LoginResult] {
return [.IncorrectFormatNoPassword, .IncorrectFormatTooShortPassword, .IncorrectFormatWrongEmailFormat]
}
var key: String {
switch self {
case IncorrectFormatNoPassword: return "login.result.error.incorrectformat.nopassword"
case IncorrectFormatTooShortPassword: return "login.result.error.incorrectformat.tooshortpassword"
case IncorrectFormatWrongEmailFormat: return "login.result.error.incorrectformat.wrongemailformat"
case NoInternetConnection: return "login.result.error.nointernetconnection"
case ServerNotReachable: return "login.result.error.servernotreachable"
case WrongCredentials: return "login.result.error.wrongcredentials"
case SuccessfulLogin: return "login.result.success"
case UnknownError(_): return ""
}
}
var title: String {
if case .UnknownError(_) = self {
return "login.result.error.unknown.title".localizedString
}
return "\(key).title".localizedString
}
var message: String {
if case .UnknownError(let message) = self {
return message ?? "login.result.error.unknown.message".localizedString
}
return "\(key).message".localizedString
}
var buttons: [String] {
switch self {
case .WrongCredentials: return [
"login.result.button.forgotpassword".localizedString
]
default: return []
}
}
var success: Bool {
if case LoginResult.SuccessfulLogin = self {
return true
}
return false
}
}
public static let sharedInstance : KAAuthenticationManager = KAAuthenticationManager()
override init() {
super.init()
NSUserDefaults.standardUserDefaults().registerDefaults([
firstLoginKey: false
])
}
public weak var delegate: KAAuthenticationManagerDelegate?
public var supportForgetPassword: Bool = true
public var minimumPasswordLength: Int = 6
private var visibleResult: LoginResult? { didSet { if visibleResult == nil { visibleEmail = nil } } }
private var visibleEmail: String?
private var dismissCallback: (() -> Void)?
private let firstLoginKey: String = "ka.authenticationmanager.firstlogin"
private var firstLogin: Bool {
get { return NSUserDefaults.standardUserDefaults().boolForKey(firstLoginKey) }
set {
NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: firstLoginKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
public func show() {
}
public func checkLoginInput(
email: String,
password: String,
serverLoginBlock: ((loginCompletionHandler: (LoginResult -> Void)) -> Void)? = nil,
resultBlock: ((LoginResult) -> Bool))
-> Bool {
if visibleEmail != nil { return false }
visibleEmail = email
let handleLoginResult = {
(result: LoginResult) -> Void in
if resultBlock(result) {
// If returned true, show alert
self.showError(forResultType: result)
self.visibleResult = result
} else {
self.visibleResult = nil
}
}
// Check format
for formatErrorType in LoginResult.formatErrorTypes {
if hasFormatError(inEmail: email, password: password, forResultType: formatErrorType) {
handleLoginResult(formatErrorType)
return false
}
}
if !Reachability.isConnectedToNetwork() {
// No internet connection
handleLoginResult(LoginResult.NoInternetConnection)
return false
}
// Try to log in
let loginCompletion = {
(result: LoginResult) -> Void in
handleLoginResult(result)
// Check success & first login
if result.success && self.firstLogin {
self.delegate?.showLicence()
self.firstLogin = false
}
}
if let serverLoginBlock = serverLoginBlock {
serverLoginBlock(loginCompletionHandler: loginCompletion)
} else {
delegate?.serverLogin(
email,
password: password,
loginCompletionHandler: loginCompletion
)
}
return true
}
private func hasFormatError(inEmail email: String, password: String, forResultType result: LoginResult) -> Bool {
switch result {
case .IncorrectFormatNoPassword: return password.characters.count == 0
case .IncorrectFormatTooShortPassword: return password.characters.count < minimumPasswordLength
case .IncorrectFormatWrongEmailFormat: return !email.isValidEmail
default: return false
}
}
private func showError(forResultType result: LoginResult) {
let alertView = UIAlertView(
title: result.title,
message: result.message,
delegate: self,
cancelButtonTitle: "login.result.button.ok".localizedString)
for button in result.buttons {
alertView.addButtonWithTitle(button)
}
alertView.show()
}
public func showLogin(fromViewController viewController: UIViewController) {
let loginController = UIAlertController(
title: "login.title".localizedString,
message: "login.message".localizedString,
preferredStyle: UIAlertControllerStyle.Alert)
var emailTextField: UITextField!
var passwordTextField: UITextField!
loginController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "login.email.placeholder".localizedString
emailTextField = textField
}
loginController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.placeholder = "login.password.placeholder".localizedString
textField.secureTextEntry = true
passwordTextField = textField
}
loginController.addAction(
UIAlertAction(
title: "login.button.login".localizedString,
style: UIAlertActionStyle.Default,
handler: { (action) -> Void in
self.checkLoginInput(emailTextField.text!, password: passwordTextField.text!, resultBlock: { (loginResult) -> Bool in
if !loginResult.success {
self.dismissCallback = {
viewController.presentViewController(loginController, animated: true, completion: nil)
}
return true
}
return false
})
return
})
)
if supportForgetPassword {
loginController.addAction(UIAlertAction(
title: "login.button.forgetpassword".localizedString,
style: UIAlertActionStyle.Destructive,
handler: { (action) -> Void in
if self.hasFormatError(inEmail: emailTextField.text ?? "", password: passwordTextField.text ?? "", forResultType: .IncorrectFormatWrongEmailFormat) {
self.dismissCallback = {
viewController.presentViewController(loginController, animated: true, completion: nil)
}
self.showError(forResultType: .IncorrectFormatWrongEmailFormat)
} else {
self.delegate?.forgotPassword(emailTextField.text!, forgotCompletionHandler: { () -> Void in
})
}
return
}))
}
viewController.presentViewController(loginController, animated: true, completion: nil)
}
}
extension KAAuthenticationManager: UIAlertViewDelegate {
public func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if let result = visibleResult where buttonIndex != alertView.cancelButtonIndex {
if case .WrongCredentials = result {
}
} else {
self.dismissCallback?()
self.dismissCallback = nil
}
visibleResult = nil
}
}
private extension String {
var isValidEmail: Bool {
let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluateWithObject(self)
}
}
public var PodBundle: NSBundle = {
if let path = NSBundle(forClass: KAAuthenticationManager.self)
.pathForResource("KAAuthenticationManager", ofType: "bundle"),
let bundle = NSBundle(path: path) {
return bundle
}
return NSBundle.mainBundle()
}()
private extension String {
var localizedString: String {
return NSLocalizedString(self, tableName: "Localizable", bundle: PodBundle, value: "", comment: "")
}
}
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
|
a69da037bcbb5b33189782c9231225a6
| 34.768328 | 169 | 0.582356 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/DebugInfo/struct_resilience.swift
|
apache-2.0
|
22
|
// RUN: %empty-directory(%t)
//
// Compile the external swift module.
// RUN: %target-swift-frontend -g -emit-module -enable-library-evolution \
// RUN: -emit-module-path=%t/resilient_struct.swiftmodule \
// RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
//
// RUN: %target-swift-frontend -g -I %t -emit-ir -enable-library-evolution %s \
// RUN: -o - | %FileCheck %s
//
import resilient_struct
// CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience9takesSizeyy010resilient_A00D0VF"(%swift.opaque* noalias nocapture %0)
// CHECK-LLDB-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience9takesSizeyy010resilient_A00D0VF"(%T16resilient_struct4SizeV* noalias nocapture dereferenceable({{8|16}}) %0)
public func takesSize(_ s: Size) {}
// CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience1fyyF"()
// CHECK-LLDB-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience1fyyF"()
func f() {
let s1 = Size(w: 1, h: 2)
takesSize(s1)
// CHECK: %[[ADDR:.*]] = alloca i8*
// CHECK: call void @llvm.dbg.declare(metadata i8** %[[ADDR]],
// CHECK-SAME: metadata ![[V1:[0-9]+]],
// CHECK-SAME: metadata !DIExpression(DW_OP_deref))
// CHECK: %[[S1:.*]] = alloca i8,
// CHECK: store i8* %[[S1]], i8** %[[ADDR]]
}
f()
// CHECK: ![[TY:[0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Size",
// CHECK: ![[LET_TY:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type,
// CHECK-SAME: baseType: ![[TY:[0-9]+]])
// CHECK: ![[V1]] = !DILocalVariable(name: "s1", {{.*}}type: ![[LET_TY]])
|
e06fa87c39bda015b8e4cb019df28abc
| 44.138889 | 179 | 0.615385 | false | false | false | false |
Xgbn/Swift
|
refs/heads/master
|
CollectionView/CollectionView/ViewController.swift
|
gpl-3.0
|
7
|
//
// ViewController.swift
// CollectionView
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// 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 UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var items : NSArray = [UIImage(named:"image1.jpg")!,UIImage(named:"image2.jpg")!,UIImage(named:"image3.jpg")!,UIImage(named:"image4.jpg")!,UIImage(named:"image5.jpg")!,UIImage(named:"image6.jpg")!,UIImage(named:"image7.jpg")!,UIImage(named:"image8.jpg")!,UIImage(named:"image9.jpg")!]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count * 5
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let identifier: String = "CollectionCell"
let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath)
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = items.objectAtIndex(indexPath.row%9) as? UIImage
return cell
}
}
|
b8ed9f7cda77141093e58e329c9962de
| 35.213115 | 288 | 0.699864 | false | false | false | false |
comyar/Chronos-Swift
|
refs/heads/master
|
Chronos/TimerInternal.swift
|
mit
|
3
|
//
// TimerInternal.swift
// Chronos
//
// Created by Andrew Chun on 4/14/15.
// Copyright (c) 2015 com.comyarzaheri. All rights reserved.
//
// MARK:- Imports
import Foundation
// MARK:- State struct
internal struct State {
static let paused: Int32 = 0
static let running: Int32 = 1
static let invalid: Int32 = 0
static let valid: Int32 = 1
}
// Mark:- Constants and Functions
internal func startTime(_ interval: Double, now: Bool) -> DispatchTime {
return DispatchTime.now() + Double(now ? 0 : Int64(interval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
}
// MARK:- Type Aliases
/**
The closure to execute when the timer fires.
- parameter timer: The timer that fired.
- parameter count: The current invocation count. The first count is 0.
*/
public typealias ExecutionClosure = ((RepeatingTimer, Int) -> Void)
|
31a7b65e1e6ca3b46d06e62dd5258a24
| 20.75 | 111 | 0.674713 | false | false | false | false |
pierrewehbe/MyVoice
|
refs/heads/master
|
MyVoice/VC_Recorder.swift
|
mit
|
1
|
//
// VC_Recorder.swift
// MyVoice
//
// Created by Pierre on 11/15/16.
// Copyright © 2016 Pierre. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import AVFoundation
//TODO
/*
- Give option to cancel from saving then to continue again / delete / Save
*/
// Initialization of some variable
var RecordButtonState : RecordBtnState = .Record
var meterTimer:Timer!
var soundFileURL:URL!
var currentFileName : String = ""
var directoryToSave : String = "Files/"
// StoryBoard ID = 1
class VC_Recorder: UIViewController , AVAudioPlayerDelegate , AVAudioRecorderDelegate {
//Audio
var audioPlayer : AVAudioPlayer?
var audioRecorder : AVAudioRecorder?
var DirectoryStack : StringStack = StringStack()
var flags : [TimeInterval] = []
// MARK: Toolbar
@IBOutlet weak var TopNavigationBar: UINavigationBar!
// Down Toolbar
@IBOutlet weak var Toolbar_Files: UIBarButtonItem!
@IBOutlet weak var Toolbar_Record: UIBarButtonItem!
@IBOutlet weak var Toolbar_Settings: UIBarButtonItem!
// MARK: PickerView
var pickerData: [String] = [String]()
// MARK: Buttons Labels
@IBOutlet weak var Button_Done: UIButton!
@IBOutlet weak var Button_Record: UIButton!
@IBOutlet weak var Button_Flag: UIButton!
@IBOutlet weak var Button_Play: UIButton!
@IBOutlet weak var Button_PausePlayer: UIButton!
@IBOutlet weak var Button_Delete: UIButton!
func updateRecordButtonAtExit(){
RecordButtonState = .Continue
self.audioRecorder?.pause()
let StateOfRecordBtn = NSEntityDescription.insertNewObject(forEntityName: "StateOfRecordBtn", into: context)
StateOfRecordBtn.setValue( "Continue" , forKey: "state")
// print("Last state Saved was \(RecordButtonState)")
//FIXME: Recording was not working since The audioRecoder is still nil
//FIXME: I will be saving my temp record in a specific file, if when I enter the fle alreay exists, then I need to continue recording from it
//Else it means I am done recording and have copied it in the All fles location at least
}
//MARK: Text Labels
@IBOutlet weak var Label_Time: UILabel!
//MARK: Preparing Entering and Exiting
override func viewDidLoad() {
super.viewDidLoad()
isAppAlreadyLaunchedOnce(Done: Button_Done,Record: Button_Record,Flag: Button_Flag)
//Initialized some buttons
Button_Play.isEnabled = false
Button_PausePlayer.isEnabled = false
Button_PausePlayer.isHidden = true
// Connect data:
if audioRecorder != nil{
meterTimer = Timer.scheduledTimer(timeInterval: 0.1,
target:self,
selector:#selector(VC_Recorder.updateAudioMeter(_:)),
userInfo:nil,
repeats:true)
let min = Int((audioRecorder?.currentTime)! / 60)
let sec = Int((audioRecorder?.currentTime.truncatingRemainder(dividingBy: 60))!)
let s = String(format: "%02d:%02d", min, sec)
Label_Time.text = s
}else{
Label_Time.text = defaultTime
}
//Create a Userfefault to keep track from last time I was recording
if ( myUserDefaults.bool(forKey: "wasRecording")){
Button_Record.setTitle("Continue", for: UIControlState())
}
//print ( "State is \(RecordButtonState)")
colorStatusBar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
// audioPlayer = nil
// audioRecorder = nil
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated) // make sure super class are being called
self.navigationController?.isNavigationBarHidden = true
if currentlySaving{
//print("I was trying to save previously")
Keep()
currentlySaving = false
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
updateBtnStateInCoreData(Done: Button_Done, Record: Button_Record, Flag: Button_Flag)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == RtoF {
if let destinationVC = segue.destination as? VC_Files {
destinationVC.audioPlayer = self.audioPlayer
destinationVC.audioRecorder = self.audioRecorder
destinationVC.DirectoryStack = self.DirectoryStack
destinationVC.flags = self.flags
}
// example to pass values between segues
}else if segue.identifier == RtoS {
if let destinationVC = segue.destination as? VC_Settings {
destinationVC.audioPlayer = self.audioPlayer
destinationVC.audioRecorder = self.audioRecorder
destinationVC.DirectoryStack = self.DirectoryStack
destinationVC.flags = self.flags
}
// example to pass values between segues
}
//print(segue.identifier!)
}
//MARK: Buttons Actions
@IBAction func Action_Done(_ sender: UIButton) {
audioRecorder?.pause()
RecordButtonState = .Continue
Button_Record.setTitle("Continue", for: UIControlState())
Button_Record.setImage(UIImage(named:"Mic_ToolBar"), for: .normal)
Button_Flag.isEnabled = false;
colorStatusBar()
Save()
}
@IBAction func Action_Record(_ sender: UIButton){
PrintAction()
Button_Done.isEnabled = true
//If I was playing and then chose to record at the same time
if audioPlayer != nil && (audioPlayer?.isPlaying)! {
audioPlayer?.stop()
}
// If nothing has been recorded yet
if audioRecorder == nil {
Button_Play.isEnabled = false
Button_Done.isEnabled = true
//print ("audio recorder is nil")
SwitchBtnState(Record : Button_Record)
recordWithPermission(true)
Button_Flag.isEnabled = true;
return
}
// I am recording + already have some data
if audioRecorder != nil && (audioRecorder?.isRecording)! { // Want to pause
SwitchBtnState(Record : Button_Record)
Button_Play.isEnabled = true
Button_Flag.isEnabled = false;
audioRecorder?.pause()
colorStatusBar()
} else { // not nil and not recording ( paused )
SwitchBtnState(Record : Button_Record)
Button_Play.isEnabled = false
Button_Done.isEnabled = true
Button_Flag.isEnabled = true;
//audioRecorder?.record()
//print("Paused, want to continue the timer")
//print("Current State is \(RecordButtonState)")
recordWithPermission(false)
}
// TODO Need to prompt user to save or delete
//TODO Button_Done.isEnabled = false Need to put it after we save the file so as to disable this button
}
@IBAction func Action_Play(_ sender: UIButton) {
setSessionPlayback()
play()
Button_Play.isHidden = true
Button_PausePlayer.isHidden = false
}
//FIXME: Maybe I should empty garbage after startin anew record so I can still hear after I have saved the file
@IBAction func Action_PausePlayer(_ sender: UIButton) {
self.audioPlayer?.pause()
Button_Play.isHidden = false
Button_PausePlayer.isHidden = true
}
@IBAction func Action_Flag(_ sender: UIButton) {
flags.append((audioRecorder!.currentTime))
}
@IBAction func Action_Delete(_ sender: UIButton) {
Delete()
}
//MARK: AVRecorder Helper Functions
func play() {
var url:URL?
if audioRecorder != nil {
//url = audioRecorder?.url
//FIXME: I cannot play a file that is paused - it will always start from the beginning
//url = soundFileURL!
} else {
url = soundFileURL!
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: url!)
Button_Done.isEnabled = true
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
audioPlayer?.volume = 1.0
audioPlayer?.play()
Button_Play.isEnabled = true
Button_PausePlayer.isEnabled = true
Button_Done.isEnabled = false
} catch let error as NSError {
audioPlayer = nil
print(error.localizedDescription)
}
}
func Save(){
// iOS8 and later
let alert = UIAlertController(title: "Recorder",
message: "Finished Recording",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Keep", style: .default, handler: {action in
self.Keep()
}))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: {action in
self.Delete()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {action in
self.Cancel()
}))
self.present(alert, animated:true, completion:nil)
}
func Keep(){
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
//let secondTextField = alertController.textFields![1] as UITextField
self.KeepHelper(txt1: firstTextField)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Name"
//FIXME: Must not alow them to put '.' character
}
// alertController.addTextField { (textField : UITextField!) -> Void in
// textField.placeholder = "Enter Second Name"
// }
alertController.addAction(UIAlertAction(title: "Change Directory", style: .default, handler: {action in
self.ChangeDirectory()
}))
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func updateCoreDataAudioFile(date : String, dir : String, dur :String, name : String){
//print ("Before : " + dir )
let dire = dir[7..<dir.length] // since .absolute string will add file:// at the beginning
let AudioFile = NSEntityDescription.insertNewObject(forEntityName: "AudioFile", into: context)
AudioFile.setValue( date , forKey: "dateOfCreation")
AudioFile.setValue( dire , forKey: "directory")
AudioFile.setValue( dur , forKey: "duration")
AudioFile.setValue( name , forKey: "name")
AudioFile.setValue( flags , forKey: "flags")
//print("Saved Audio info dir : " + dire)
do{
try context.save()
}catch let error as NSError{
print (error)
}
}
func KeepHelper(txt1 : UITextField){
self.audioRecorder?.stop()
let curr = myUserDefaults.integer(forKey: "NumberOfRecordings") + 1
// By default , directoryToSave = Files/ which is the container File
//print ("directoryTosave is : " + directoryToSave)
var newname : String = ""
if fileExists(Directory: "/" + directoryToSave ){
if txt1.text != ""{
newname = directoryToSave + txt1.text! + ".m4a"
renameItem(oldName: "/" + garbageDirectory + currentFileName, newName: "/" + newname )
soundFileURL = appDocumentDirectory.appendingPathComponent(newname)
updateCoreDataAudioFile(date: currentFileName , dir: soundFileURL.absoluteString ,dur: "duration", name: txt1.text!) //FIXME: duration
}else{
newname = directoryToSave + "Recording-\(curr).m4a"
renameItem(oldName: "/" + garbageDirectory + currentFileName, newName: "/" + newname )
soundFileURL = appDocumentDirectory.appendingPathComponent(newname)
updateCoreDataAudioFile(date: currentFileName , dir: soundFileURL.absoluteString ,dur: "duration", name: "Recording-\(curr)")
}
}else{
// It has been modified //FIXME: fix initial condition (otherFiles) I only want to create a directory if it doesn't exist
createNewDirectory(newDir: defaultFilesDirectory + directoryToSave)
if txt1.text != ""{
newname = directoryToSave + txt1.text! + ".m4a"
renameItem(oldName: "/" + garbageDirectory + currentFileName, newName: "/" + newname )
soundFileURL = appDocumentDirectory.appendingPathComponent(newname)
updateCoreDataAudioFile(date: currentFileName , dir: soundFileURL.absoluteString ,dur: "duration", name: txt1.text!)
}else{
newname = directoryToSave + "Recording-\(curr).m4a"
renameItem(oldName: "/" + garbageDirectory + currentFileName, newName: "/" + newname )
soundFileURL = appDocumentDirectory.appendingPathComponent(newname)
updateCoreDataAudioFile(date: currentFileName , dir: soundFileURL.absoluteString ,dur: "duration", name: "Recording-\(curr)")
}
}
var temp = directoryToSave
temp.remove(at: temp.index(before: temp.endIndex))
let containerFileDir = appDocumentDirectory.appendingPathComponent(temp).path
//print ("Container is : " + containerFileDir)
let nameOfFile = newname.substring(from: directoryToSave.length)
var currentOrder : [String] = myUserDefaults.array(forKey: containerFileDir) as! [String]
// print ("current Order" )
//print (currentOrder)
currentOrder.append(nameOfFile)
myUserDefaults.set(currentOrder, forKey: containerFileDir)
var afterOrder : [String] = myUserDefaults.array(forKey: containerFileDir) as! [String]
// print ("after Order" )
//print (afterOrder)
myUserDefaults.set(curr, forKey: "NumberOfRecordings")
if meterTimer != nil{
meterTimer.invalidate()
// print( "Timer was invalidated" )
}
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(false)
RecordButtonState = .Record
audioRecorder?.stop()
colorStatusBar()
Button_Record.setTitle("Record", for: UIControlState())
Button_Play.isEnabled = true
Button_PausePlayer.isEnabled = true
Button_Done.isEnabled = false
} catch let error as NSError {
print("could not make session inactive")
print(error.localizedDescription)
}
self.audioRecorder = nil // Akhou el charmouta ca ma niquer
//directoryToSave = "otherFiles"
// Make sure garbage is empty
deleteDirectory(Directory: "/" + garbageDirectory )
createNewDirectory(newDir: garbageDirectory)
}
func ChangeDirectory(){
//FIXME: segue to Files + carefull how I am gonna initialize directoryToSave
changingDirectory = true;
performSegue(withIdentifier: RtoF, sender: self)
// let files = listContentsAtDirectory(Directory: "/Files")
// pickerData = [] // reinitialize
// for file in files {
// if file.description == "garbage" || file.description.contains(".") {
// //skip
// }else{
// pickerData.append(file.description)
// }
// }
// //pickerData.append("Create New Directory")
// pickerData.sort()
}
func Delete(){
let alertController = UIAlertController(title: "Are you sure?", message: "", preferredStyle: .alert)
let deleteAction = UIAlertAction(title: "Yes", style: .default, handler: {
alert -> Void in
self.DeleteHelper()
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(deleteAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func DeleteHelper(){
self.audioRecorder?.stop()
if meterTimer != nil{
meterTimer.invalidate()
//print( "Timer was invalidated" )
}
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(false)
RecordButtonState = .Record
colorStatusBar()
audioRecorder?.stop()
Button_Record.setTitle("Record", for: UIControlState())
Button_Play.isEnabled = false
Button_PausePlayer.isEnabled = false
Button_Done.isEnabled = false
} catch let error as NSError {
print("could not make session inactive")
print(error.localizedDescription)
}
self.audioRecorder?.deleteRecording()
Label_Time.text = defaultTime
}
func Cancel(){
}
func recordWithPermission(_ setup:Bool) {
let session:AVAudioSession = AVAudioSession.sharedInstance()
// ios 8 and later
if (session.responds(to: #selector(AVAudioSession.requestRecordPermission(_:)))) {
AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
if granted {
print("Permission to record granted")
self.setSessionPlayAndRecord()
if setup {
self.setupRecorder()
print("Preparing the recording of a new file")
}
meterTimer = Timer.scheduledTimer(timeInterval: 0.1, // after 0.1 sec, fires what is in selector
target:self,
selector:#selector(VC_Recorder.updateAudioMeter(_:)),
userInfo:nil,
repeats:true)
self.audioRecorder?.record() // Continue
self.colorStatusBar()
} else {
print("Permission to record not granted")
}
})
} else {
print("requestRecordPermission unrecognized")
}
}
func setupRecorder() {
let format = DateFormatter()
format.dateFormat="yyyy-MM-dd-HH-mm-ss"
currentFileName = "\(format.string(from: Date()))"
//FIXME: need to create a golbal variable for the name
//FIXME: Need to play the file at the specific location garbage
//print(currentFileName)
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
soundFileURL = documentsDirectory.appendingPathComponent(garbageDirectory + currentFileName)
//Now the soundFileURL is the absolute address of the file
if FileManager.default.fileExists(atPath: soundFileURL.absoluteString) {
//FIXME: probably won't happen. want to do something about it?
print("soundfile \(soundFileURL.absoluteString) exists")
}
let recordSettings:[String : AnyObject] = [
AVFormatIDKey: NSNumber(value: kAudioFormatAppleLossless),
AVEncoderAudioQualityKey : NSNumber(value:AVAudioQuality.max.rawValue),
AVEncoderBitRateKey : NSNumber(value:320000),
AVNumberOfChannelsKey: NSNumber(value:2),
AVSampleRateKey : NSNumber(value:44100.0)
]
do {
audioRecorder = try AVAudioRecorder(url: soundFileURL, settings: recordSettings)
audioRecorder?.delegate = self
audioRecorder?.isMeteringEnabled = true
audioRecorder?.prepareToRecord() // creates/overwrites the file at soundFileURL
} catch let error as NSError {
audioRecorder = nil
print(error.localizedDescription)
}
}
func setSessionPlayAndRecord() {
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch let error as NSError {
print("could not set session category")
print(error.localizedDescription)
}
do {
try session.setActive(true)
} catch let error as NSError {
print("could not make session active")
print(error.localizedDescription)
}
}
func updateAudioMeter(_ timer:Timer) {
if let a = (audioRecorder?.isRecording) {
if a {
let min = Int((audioRecorder?.currentTime)! / 60)
let sec = Int((audioRecorder?.currentTime.truncatingRemainder(dividingBy: 60))!)
let s = String(format: "%02d:%02d", min, sec)
Label_Time.text = s
//print(s)
audioRecorder?.updateMeters()
// if you want to draw some graphics...
//var apc0 = recorder.averagePowerForChannel(0)
//var peak0 = recorder.peakPowerForChannel(0)
}
}
}
func setSessionPlayback() {
let session:AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback) //FIXME: add new options for background
} catch let error as NSError {
print("could not set session category")
print(error.localizedDescription)
}
do {
try session.setActive(true)
} catch let error as NSError {
print("could not make session active")
print(error.localizedDescription)
}
}
// MARK: AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder,
successfully flag: Bool) {
//print("Done Recording")
//print(" ")
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder,
error: Error?) {
if let e = error {
print("\(e.localizedDescription)")
}
}
// MARK: AVAudioPlayerDelegate
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
//print("Finished playing \(flag)")
let image = UIImage(named: "Mic_ToolBar")
Record.setImage(image, for: UIControlState.normal)
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
if let e = error {
print("\(e.localizedDescription)")
//FIXME: add the buttons modificatons here for done.isenable...
}
}
// MARK: Display helper Functions
func colorStatusBar(){
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
//Change status bar color
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if self.audioRecorder != nil {
//Status bar style and visibility
//if statusBar.respondsToSelector("setBackgroundColor:") {
switch RecordButtonState {
case .Record:
statusBar.backgroundColor = UIColor.black
case .Continue:
statusBar.backgroundColor = UIColor.blue
case .Pause:
statusBar.backgroundColor = UIColor.red
}
//FIXME: If I exited my app while it was at the continue state, it will bw black since the audio is nil, will need to arrange it in case I didn't took care of this case, can simply remove the condition that checks if it is nil
//}
}else{
statusBar.backgroundColor = UIColor(colorLiteralRed: 234.0, green: 79.0, blue: 63.0, alpha: 100.0)
}
}
}
// MARK: Helper functions
/*
This function will be used to keep track of the states of the record buttons from the time we first ran the program ever till the next time we used it
These boolean informations will be stored in the CoreData.
We will need to keep track of:
- The boolean buttons
*/
func isAppAlreadyLaunchedOnce( Done: UIButton , Record:UIButton , Flag:UIButton)->Bool{
if let isAppAlreadyLaunchedOnce = myUserDefaults.string(forKey: "isAppAlreadyLaunchedOnce"){
print("App already launched : \(isAppAlreadyLaunchedOnce)")
InitializeStateOfBtn(Done: Done,Record: Record,Flag: Flag)
return true
}else{
myUserDefaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
let emptyString : [String] = []
myUserDefaults.set(emptyString, forKey: appDocumentDirectory.path) // creates one for Documents
InitializeStateOfBtnFirstRun(Done: Done,Record: Record,Flag: Flag)
return false
}
}
func InitializeStateOfBtn( Done: UIButton , Record:UIButton , Flag:UIButton){
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "BtnState")
request.returnsObjectsAsFaults = false // To be able to see the data the way we saved it
do{
let results = try context.fetch(request)
if results.count > 0 { // only if non-empty
for result in results as! [NSManagedObject]
{
if let temp = result.value(forKey: "btn_Done") as? Bool {
Done.isEnabled = temp;
if (temp){
// print ("Done : True")
}else{
//print ("Done : False")
}
}
if let temp = result.value(forKey: "btn_Flag") as? Bool {
Flag.isEnabled = temp;
if (temp){
// print ("Flag : True")
}else{
//print ("Flag : False")
}
}
if let temp = result.value(forKey: "btn_Record") as? Bool {
Record.isEnabled = temp;
if (temp){
// print ("Record : True")
}else{
// print ("Record : False")
}
}
}
}
}catch let error as NSError{
//print (error.localizedDescription)
print(error.localizedDescription)
}
/*****************************************/
let request2 = NSFetchRequest<NSFetchRequestResult>(entityName: "StateOfRecordBtn")
request2.returnsObjectsAsFaults = false // To be able to see the data the way we saved it
do{
let results = try context.fetch(request2)
if results.count > 0 { // only if non-empty
for result in results as! [NSManagedObject]
{
if let temp = result.value(forKey: "state") as? String{
switch temp {
case "Record":
RecordButtonState = .Record
Record.setTitle("Record", for: UIControlState())
case "Pause":
RecordButtonState = .Pause
Record.setTitle("Pause", for: UIControlState())
case "Continue":
RecordButtonState = .Continue
Record.setTitle("Continue", for: UIControlState())
default:
print ("Type not defined for state of Record button")
}
}
}
}
}catch let error as NSError{
//print (error.localizedDescription)
print(error)
}
/*****************************************/
}
func InitializeStateOfBtnFirstRun( Done: UIButton , Record:UIButton , Flag:UIButton){
Done.isEnabled = false;
Record.isEnabled = true;
Flag.isEnabled = false;
// TODO need to take care of the colors of the buttons
// TODO need to store this data in the CoreData
print("Buttons have been initialized")
// Saving the boolean values of the button
let btnState = NSEntityDescription.insertNewObject(forEntityName: "BtnState", into: context)
btnState.setValue(Done.isEnabled, forKey: "btn_Done")
btnState.setValue(Record.isEnabled, forKey: "btn_Record")
btnState.setValue(Flag.isEnabled, forKey: "btn_Flag")
let StateOfRecordBtn = NSEntityDescription.insertNewObject(forEntityName: "StateOfRecordBtn", into: context)
StateOfRecordBtn.setValue( "Record" , forKey: "state")
RecordButtonState = .Record
do{
try context.save()
//print("BtnStates have been saved")
}catch let error as NSError{
print (error)
}
myUserDefaults.set(false, forKey: "wasRecording")
//File manager
createNewDirectory(newDir: defaultFilesDirectory)
createNewDirectory(newDir: otherFilesDirectory )
createNewDirectory(newDir: garbageDirectory)
//Track number of records so far
myUserDefaults.set(0, forKey: "NumberOfRecordings")
}
/*
This function takes care of keeping track what is the state of the button
TODO Update the picture/Color of the button
*/
func SwitchBtnState(Record : UIButton){
switch RecordButtonState {
case .Record:
RecordButtonState = .Pause
let image = UIImage(named: "Pause_Toolbar")
Record.setImage(image, for: UIControlState.normal)
Record.setTitle("Pause", for: UIControlState())
//print("From Record to Pause")
//print(" \n")
case .Pause:
RecordButtonState = .Continue
let image = UIImage(named: "Mic_ToolBar")
Record.setImage(image, for: UIControlState.normal)
Record.setTitle("Continue", for: UIControlState())
//print("From Pause to Continue")
//print(" \n")
case .Continue:
RecordButtonState = .Pause
let image = UIImage(named: "Pause_Toolbar")
Record.setImage(image, for: UIControlState.normal)
Record.setTitle("Pause", for: UIControlState())
//print("From Continue to Pause")
//print(" \n")
}
}
/*
Prints the current action that we are performing
*/
func PrintAction(){
switch RecordButtonState {
case .Record:
print("Recording...")
case .Pause:
print("Paused")
case .Continue:
print("Continued")
}
}
/*
Updates the informations in the CoreData just before leaving the View ( TODO need to put it in Segue)
*/
func updateBtnStateInCoreData( Done: UIButton , Record:UIButton , Flag:UIButton){
// Need to empty all the data before overriding it
deleteAllData(entity: "BtnState")
deleteAllData(entity: "StateOfRecordBtn")
let btnState = NSEntityDescription.insertNewObject(forEntityName: "BtnState", into: context)
btnState.setValue(Done.isEnabled, forKey: "btn_Done")
btnState.setValue(Record.isEnabled, forKey: "btn_Record")
btnState.setValue(Flag.isEnabled, forKey: "btn_Flag")
let request2 = NSFetchRequest<NSFetchRequestResult>(entityName: "StateOfRecordBtn")
request2.returnsObjectsAsFaults = false // To be able to see the data the way we saved it
do{
let results = try context.fetch(request2)
// print( results.count)
}catch{
}
let StateOfRecordBtn = NSEntityDescription.insertNewObject(forEntityName: "StateOfRecordBtn", into: context)
var tempString : String = ""
switch RecordButtonState {
case .Record:
tempString = "Record"
// print("Last State saved was : Record" )
case .Pause:
tempString = "Pause"
//print("Last State saved was : Pause" )
case .Continue:
tempString = "Continue"
// print("Last State saved was : Continue" )
}
StateOfRecordBtn.setValue( tempString , forKey: "state")
}
func deleteAllData(entity: String)
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
}
}
|
498a3eda3f8f194a74482bf2a5643d53
| 34.168687 | 238 | 0.577735 | false | false | false | false |
hrunar/BreadMaker
|
refs/heads/master
|
BreadMaker.playground/Pages/13 - Autolyse.xcplaygroundpage/Contents.swift
|
mit
|
2
|
//: [Previous](@previous)
import Interstellar
struct Dough {
let yield: Double
var mixed = false
var autolyseCompleted = false
init(yield: Double) {
self.yield = yield
}
mutating func mix() {
self.mixed = true
}
mutating func autolyse() {
self.autolyseCompleted = true
}
}
enum BakeError: ErrorType {
case MixingError
case AutolyseError
}
struct BreadMaker {
func makeBread(completion: Result<Dough> -> Void) -> Void {
print("Making bread")
let dough = Dough(yield: 1700)
//: Then we add the rest of the steps
Signal(dough)
.flatMap(mix)
.flatMap(autolyse)
.subscribe { result in
completion(result)
}
}
private func mix(var dough: Dough) -> Result<Dough> {
print("Mix")
dough.mix()
return dough.mixed ? .Success(dough) : .Error(BakeError.MixingError)
}
private func autolyse(var dough: Dough) -> Result<Dough> {
print("Autolyse")
dough.autolyse()
return dough.autolyseCompleted ? .Success(dough) : .Error(BakeError.AutolyseError)
}
}
BreadMaker().makeBread { result in
switch result {
case .Success:
print("Got bread!")
break
case .Error:
print("Error, no bread!!")
}
}
//: [Next](@next)
|
c4448841d1ca00e390680f67f29d8f11
| 19.098592 | 90 | 0.552908 | false | false | false | false |
auth0/Lock.iOS-OSX
|
refs/heads/master
|
LockTests/PasswordlessAuthenticatableErrorSpec.swift
|
mit
|
2
|
// PasswordlessAuthenticatableErrorSpec.swift
//
// Copyright (c) 2017 Auth0 (http://auth0.com)
//
// 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 Quick
import Nimble
@testable import Lock
class PasswordlessAuthenticatableErrorSpec: QuickSpec {
override func spec() {
describe("localised message response") {
it("should return default string for invalid input") {
let error = PasswordlessAuthenticatableError.nonValidInput
expect(error.localizableMessage).to(contain("SOMETHING WENT WRONG"))
}
it("should return default string for code not sent") {
let error = PasswordlessAuthenticatableError.codeNotSent
expect(error.localizableMessage).to(contain("SOMETHING WENT WRONG"))
}
it("should return specific string for invalid limnk") {
let error = PasswordlessAuthenticatableError.invalidLink
expect(error.localizableMessage).to(contain("PROBLEM WITH YOUR LINK"))
}
it("should return specific string for no signup") {
let error = PasswordlessAuthenticatableError.noSignup
expect(error.localizableMessage).to(contain("DISABLED FOR THIS ACCOUNT"))
}
}
describe("user visibility") {
it("should return false") {
let error = PasswordlessAuthenticatableError.nonValidInput
expect(error.userVisible).to(beFalse())
}
}
}
}
|
849b532aa7cf9ffb0220c95b91023309
| 39.359375 | 89 | 0.680991 | false | false | false | false |
Rypac/hn
|
refs/heads/reactive-overhaul
|
hn/FirebaseService.swift
|
mit
|
1
|
import Foundation
import RxSwift
final class FirebaseService {
typealias Item = FirebaseItem
private let apiClient: APIClient
private let decoder = JSONDecoder()
init(apiClient: APIClient) {
self.apiClient = apiClient
}
func topStories() -> Single<[Int]> {
return apiClient.get(Firebase.topStories.url)
.map { [decoder] response in
guard (200..<299).contains(response.statusCode) else {
throw APIServiceError.invalidStatusCode
}
guard let data = response.body else {
throw APIServiceError.invalidPayload
}
return try decoder.decode(data)
}
}
func item(id: Int) -> Single<Item> {
return apiClient.get(Firebase.item(id).url)
.map { [decoder] response in
guard (200..<299).contains(response.statusCode) else {
throw APIServiceError.invalidStatusCode
}
guard let data = response.body else {
throw APIServiceError.invalidPayload
}
return try decoder.decode(data)
}
}
}
|
de9cfc1ad4303b05f263d76c67b918c8
| 25.74359 | 62 | 0.643337 | false | false | false | false |
devpunk/velvet_room
|
refs/heads/master
|
Source/Model/Vita/MVitaPtpString.swift
|
mit
|
1
|
import Foundation
final class MVitaPtpString
{
private static let kBytesForSize:Int = 1
private static let kBytesPerCharacter:Int = 2
private static let kWrappingCharacter:UInt8 = 0
//MARK: private
private init() { }
private class func factoryLength(
data:Data) -> Int?
{
guard
let size:UInt8 = data.valueFromBytes()
else
{
return nil
}
let sizeInt:Int = Int(size)
let totalSize:Int = sizeInt * kBytesPerCharacter
return totalSize
}
private class func factoryString(
data:Data,
length:Int) -> String?
{
let wrappedData:Data = wrapData(
data:data,
length:length)
guard
let string:String = String(
data:wrappedData,
encoding:String.Encoding.utf16)
else
{
return nil
}
return string
}
private class func wrapData(
data:Data,
length:Int) -> Data
{
let subdataLength:Int = length - kBytesForSize
let subData:Data = data.subdata(
start:kBytesForSize,
endNotIncluding:subdataLength)
var wrappedData:Data = Data()
wrappedData.append(value:kWrappingCharacter)
wrappedData.append(subData)
return wrappedData
}
//MARK: internal
class func factoryString(
data:Data) -> String?
{
guard
let length:Int = factoryLength(data:data),
length > 0,
data.count > length,
let string:String = factoryString(
data:data,
length:length)
else
{
return nil
}
return string
}
class func factoryData(
string:String) -> Data?
{
guard
let stringData:Data = string.data(
using:String.Encoding.utf8,
allowLossyConversion:false)
else
{
return nil
}
let stringDataSize:Int = stringData.count
let stringUnsignedSize:UInt8 = UInt8(stringDataSize)
var data:Data = Data()
data.append(stringUnsignedSize)
data.append(stringData)
return data
}
}
|
bbbb99f1468bb1248e822a2eb363dbaf
| 21.087719 | 60 | 0.495234 | false | false | false | false |
sureshxaton/BackgroundUpload-CocoaLumberjack
|
refs/heads/master
|
Classes/CocoaLumberjack.swift
|
bsd-3-clause
|
2
|
// Software License Agreement (BSD License)
//
// Copyright (c) 2014-2015, Deusty, LLC
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Neither the name of Deusty nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission of Deusty, LLC.
import Foundation
import CocoaLumberjack
extension SVLogFlag {
public static func fromLogLevel(logLevel: SVLogLevel) -> SVLogFlag {
return SVLogFlag(logLevel.rawValue)
}
public init(_ logLevel: SVLogLevel) {
self = SVLogFlag(logLevel.rawValue)
}
///returns the log level, or the lowest equivalant.
public func toLogLevel() -> SVLogLevel {
if let ourValid = SVLogLevel(rawValue: self.rawValue) {
return ourValid
} else {
let logFlag = self
if logFlag & .Verbose == .Verbose {
return .Verbose
} else if logFlag & .Debug == .Debug {
return .Debug
} else if logFlag & .Info == .Info {
return .Info
} else if logFlag & .Warning == .Warning {
return .Warning
} else if logFlag & .Error == .Error {
return .Error
} else {
return .Off
}
}
}
}
public var defaultDebugLevel = SVLogLevel.Verbose
public func resetDefaultDebugLevel() {
defaultDebugLevel = SVLogLevel.Verbose
}
public func SwiftLogMacro(isAsynchronous: Bool, level: SVLogLevel, flag flg: SVLogFlag, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, tag: AnyObject? = nil, @autoclosure(escaping) #string: () -> String) {
if level.rawValue & flg.rawValue != 0 {
// Tell the SVLogMessage constructor to copy the C strings that get passed to it.
// Using string interpolation to prevent integer overflow warning when using StaticString.stringValue
let logMessage = SVLogMessage(message: string(), level: level, flag: flg, context: context, file: "\(file)", function: "\(function)", line: line, tag: tag, options: .CopyFile | .CopyFunction, timestamp: nil)
SVLog.log(isAsynchronous, message: logMessage)
}
}
public func SVLogDebug(@autoclosure(escaping) logText: () -> String, level: SVLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Debug, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func SVLogInfo(@autoclosure(escaping) logText: () -> String, level: SVLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Info, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func SVLogWarn(@autoclosure(escaping) logText: () -> String, level: SVLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Warning, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func SVLogVerbose(@autoclosure(escaping) logText: () -> String, level: SVLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = true) {
SwiftLogMacro(async, level, flag: .Verbose, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
public func SVLogError(@autoclosure(escaping) logText: () -> String, level: SVLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = __FILE__, function: StaticString = __FUNCTION__, line: UWord = __LINE__, tag: AnyObject? = nil, asynchronous async: Bool = false) {
SwiftLogMacro(async, level, flag: .Error, context: context, file: file, function: function, line: line, tag: tag, string: logText)
}
/// Analogous to the C preprocessor macro `THIS_FILE`.
public func CurrentFileName(fileName: StaticString = __FILE__) -> String {
// Using string interpolation to prevent integer overflow warning when using StaticString.stringValue
return "\(fileName)".lastPathComponent.stringByDeletingPathExtension
}
|
6571fae155f9d41cbdebff6007403941
| 54.066667 | 279 | 0.680791 | false | false | false | false |
STShenZhaoliang/Swift2Guide
|
refs/heads/master
|
Swift2Guide/Swift100Tips/Swift100Tips/DefaultController.swift
|
mit
|
1
|
//
// DefaultController.swift
// Swift100Tips
//
// Created by 沈兆良 on 16/5/30.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class DefaultController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/// Returns a localized string, using the main bundle if one is not specified.
// public func NSLocalizedString(key: String, tableName: String? = default, bundle: NSBundle = default, value: String = default, comment: String) -> String
// 默认参数写的是 default,这是含有默认参数的方法所生成的 Swift 的调用接口。当我们指定一个编译时就能确定的常量来作为默认参数的取值时,这个取值是隐藏在方法实现内部,而不应该暴露给其他部分。与 NSLocalizedString 很相似的还有 Swift 中的各类断言.
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sayHello1(str1: String = "Hello", str2: String, str3: String) {
print(str1 + str2 + str3)
}
@warn_unused_result
func sayHello2(str1: String,
str2: String,
str3: String = "World") {
// print(str1 + str2 + str3)
}
/*
// 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.
}
*/
}
|
b1edfa376f5d41fe8a46e5ea047e88ca
| 28.903846 | 162 | 0.659807 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/Generics/minimize_superclass_unification_generic_1.swift
|
apache-2.0
|
6
|
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
class A<T> {}
class B<T> : A<T> {}
class C<T, U> : A<(T, U)> {}
class D<T, U> : A<U> {}
// ----------------
protocol P1 {
associatedtype T where T : A<X>
associatedtype X
}
protocol Q1 {
associatedtype T where T : B<Y>
associatedtype Y
}
// CHECK-LABEL: .R1a@
// CHECK-NEXT: Requirement signature: <Self where Self.[R1a]T : P1, Self.[R1a]T : Q1>
protocol R1a {
associatedtype T where T : P1, T : Q1, T.X == T.Y
}
// CHECK-LABEL: .R1b@
// CHECK-NEXT: Requirement signature: <Self where Self.[R1b]T : P1, Self.[R1b]T : Q1>
protocol R1b {
associatedtype T where T : P1, T : Q1
}
// ----------------
protocol P2 {
associatedtype T where T : B<X>
associatedtype X
}
protocol Q2 {
associatedtype T where T : A<Y>
associatedtype Y
}
// CHECK-LABEL: .R2a@
// CHECK-NEXT: Requirement signature: <Self where Self.[R2a]T : P2, Self.[R2a]T : Q2>
protocol R2a {
associatedtype T where T : P2, T : Q2, T.X == T.Y
}
// CHECK-LABEL: .R2b@
// CHECK-NEXT: Requirement signature: <Self where Self.[R2b]T : P2, Self.[R2b]T : Q2>
protocol R2b {
associatedtype T where T : P2, T : Q2
}
// ----------------
protocol P3 {
associatedtype T where T : A<X>
associatedtype X
}
protocol Q3 {
associatedtype T where T : C<Y, Z>
associatedtype Y
associatedtype Z
}
// CHECK-LABEL: .R3a@
// CHECK-NEXT: Requirement signature: <Self where Self.[R3a]T : P3, Self.[R3a]T : Q3>
protocol R3a {
associatedtype T where T : P3, T : Q3, T.X == (T.Y, T.Z)
}
// CHECK-LABEL: .R3b@
// CHECK-NEXT: Requirement signature: <Self where Self.[R3b]T : P3, Self.[R3b]T : Q3>
protocol R3b {
associatedtype T where T : P3, T : Q3
}
// ----------------
protocol P4 {
associatedtype T where T : C<X, Y>
associatedtype X
associatedtype Y
}
protocol Q4 {
associatedtype T where T : A<Z>
associatedtype Z
}
// CHECK-LABEL: .R4a@
// CHECK-NEXT: Requirement signature: <Self where Self.[R4a]T : P4, Self.[R4a]T : Q4>
protocol R4a {
associatedtype T where T : P4, T : Q4, T.Z == (T.X, T.Y)
}
// CHECK-LABEL: .R4b@
// CHECK-NEXT: Requirement signature: <Self where Self.[R4b]T : P4, Self.[R4b]T : Q4>
protocol R4b {
associatedtype T where T : P4, T : Q4
}
// ----------------
protocol P5 {
associatedtype T where T : A<X>
associatedtype X
}
protocol Q5 {
associatedtype T where T : D<Y, Z>
associatedtype Y
associatedtype Z
}
// CHECK-LABEL: .R5a@
// CHECK-NEXT: Requirement signature: <Self where Self.[R5a]T : P5, Self.[R5a]T : Q5>
protocol R5a {
associatedtype T where T : P5, T : Q5, T.X == T.Z
}
// CHECK-LABEL: .R5b@
// CHECK-NEXT: Requirement signature: <Self where Self.[R5b]T : P5, Self.[R5b]T : Q5>
protocol R5b {
associatedtype T where T : P5, T : Q5
}
// ----------------
protocol P6 {
associatedtype T where T : D<X, Y>
associatedtype X
associatedtype Y
}
protocol Q6 {
associatedtype T where T : A<Z>
associatedtype Z
}
// CHECK-LABEL: .R6a@
// CHECK-NEXT: Requirement signature: <Self where Self.[R6a]T : P6, Self.[R6a]T : Q6>
protocol R6a {
associatedtype T where T : P6, T : Q6, T.Z == T.Y
}
// CHECK-LABEL: .R6b@
// CHECK-NEXT: Requirement signature: <Self where Self.[R6b]T : P6, Self.[R6b]T : Q6>
protocol R6b {
associatedtype T where T : P6, T : Q6
}
// ----------------
// CHECK-LABEL: .P7@
// CHECK-NEXT: Requirement signature: <Self where Self.[P7]V : P1, Self.[P7]W == Self.[P7]V.[P1]X>
protocol P7 {
associatedtype V where V : P1, V.T : A<W>
associatedtype W
}
|
f6f9eca48662e033a9d3040038f0c1e1
| 18.026738 | 98 | 0.617093 | false | false | false | false |
mluisbrown/Memories
|
refs/heads/master
|
Memories/Settings/AppearanceViewController.swift
|
mit
|
1
|
import UIKit
import Core
import ReactiveCocoa
import ReactiveSwift
enum Appearance: String {
case dark
case light
case system
}
class AppearanceViewController: UITableViewController {
@IBOutlet weak var darkCell: UITableViewCell!
@IBOutlet weak var lightCell: UITableViewCell!
@IBOutlet weak var systemCell: UITableViewCell!
private var cells: [UITableViewCell: Appearance] = [:]
private let appearanceObserver: Signal<Appearance, Never>.Observer
private let viewModel: AppearanceViewModel
required init?(coder aDecoder: NSCoder) {
let selectedAppearance: Signal<Appearance, Never>
(selectedAppearance, appearanceObserver) = Signal<Appearance, Never>.pipe()
viewModel = AppearanceViewModel(
updateWindowStyle: Current.updateAppearance
)
super.init(coder: aDecoder)
bindViewModel(selectedAppearance: selectedAppearance)
}
private func bindViewModel(selectedAppearance: Signal<Appearance, Never>) {
viewModel.appearance <~ selectedAppearance
selectedAppearance.observeValues { appearance in
self.updateCells(appearance: appearance)
}
}
private func updateCells(appearance: Appearance) {
cells.keys.forEach { cell in
cell.accessoryType = .none
}
cells.forEach { cell, cellAppearance in
guard cellAppearance == appearance else {
return
}
cell.accessoryType = .checkmark
}
}
override func viewDidLoad() {
cells = [
darkCell: .dark,
lightCell: .light,
systemCell: .system
]
updateCells(appearance: viewModel.appearance.value)
}
// MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath),
let appearance = cells[cell]
else { return }
appearanceObserver.send(value: appearance)
}
}
struct AppearanceViewModel {
static let appearanceKey = "appearance"
let appearance = MutableProperty<Appearance>(.system)
init(
updateWindowStyle: @escaping (Appearance) -> Void
) {
if let setting = Current.userDefaults.string(forKey: AppearanceViewModel.appearanceKey),
let appearance = Appearance.init(rawValue: setting) {
self.appearance.value = appearance
}
self.appearance.signal
.observeValues { appearance in
updateWindowStyle(appearance)
}
}
}
|
25d27d54bd56fac479ebc06a685daf1a
| 27.117021 | 96 | 0.653046 | false | false | false | false |
koara/koara-swift
|
refs/heads/master
|
Tests/Html5Renderer.swift
|
apache-2.0
|
1
|
import Koara
import Foundation
class Html5Renderer : Renderer {
var output : String = ""
var level : Int = 0
var listSequence = Array<Int>();
public var hardWrap : Bool = false
func visitDocument(node: Document) {
output = ""
node.childrenAccept(renderer: self);
}
func visitHeading(node: Heading) {
output += indent() + "<h" + String(describing: node.value) + ">"
node.childrenAccept(renderer: self);
output += "</h" + String(describing: node.value) + ">\n"
if !node.isNested() {
output += "\n"
}
}
func visitBlockQuote(node: BlockQuote) {
output += indent() + "<blockquote>"
if(node.children.count > 0) { output += "\n" }
level += 1
node.childrenAccept(renderer: self);
level -= 1
output += indent() + "</blockquote>\n"
if(!node.isNested()) {
output += "\n"
}
}
func visitListBlock(node: ListBlock) {
listSequence.append(0)
let tag = node.ordered! ? "ol" : "ul"
output += indent() + "<" + tag + ">\n"
level += 1
node.childrenAccept(renderer: self);
level -= 1
output += indent() + "</" + tag + ">\n"
if(!node.isNested()) {
output += "\n"
}
_ = listSequence.popLast()
}
func visitListItem(node: ListItem) {
let seq = listSequence.last! + 1
listSequence[listSequence.count - 1] = seq
output += indent() + "<li"
if(node.number > 0 && seq != node.number) {
output += " value=\"\(node.number)\""
listSequence.append(node.number)
}
output += ">"
if(node.children.count > 0) {
let block = (String(describing: node.children.first!) == "Koara.Paragraph"
|| String(describing: node.children.first!) == "Koara.BlockElement");
if(node.children.count > 1 || !block) { output += "\n"; }
level += 1
node.childrenAccept(renderer: self);
level -= 1
if(node.children.count > 1 || !block) { output += indent(); }
}
output += "</li>\n"
}
func visitCodeBlock(node: CodeBlock) {
output += indent() + "<pre><code"
if ((node.language) != nil) {
output += " class=\"language-" + escape(text: node.language) + "\""
}
output += ">"
output += escape(text: node.value as! String) + "</code></pre>\n"
if(!node.isNested()) {
output += "\n"
}
}
func visitParagraph(node: Paragraph) {
if(node.isNested() && (node.parent is ListItem) && node.isSingleChild()) {
node.childrenAccept(renderer: self);
} else {
output += indent() + "<p>"
node.childrenAccept(renderer: self)
output += "</p>\n"
if(!node.isNested()) {
output += "\n"
}
}
}
func visitBlockElement(node: BlockElement) {
if(node.isNested() && (node.parent is ListItem) && node.isSingleChild()) {
node.childrenAccept(renderer: self);
} else {
output += indent()
node.childrenAccept(renderer: self)
if(!node.isNested()) {
output += "\n"
}
}
}
func visitImage(node: Image) {
output += "<img src=\"" + escapeUrl(text: node.value as! String) + "\" alt=\"";
node.childrenAccept(renderer: self);
output += "\" />";
}
func visitLink(node: Link) {
output += "<a href=\"\(escapeUrl(text: node.value as! String))\">";
node.childrenAccept(renderer: self);
output += "</a>";
}
func visitStrong(node: Strong) {
output += "<strong>"
node.childrenAccept(renderer: self)
output += "</strong>"
}
func visitEm(node: Em) {
output += "<em>"
node.childrenAccept(renderer: self)
output += "</em>"
}
func visitCode(node: Code) {
output += "<code>"
node.childrenAccept(renderer: self);
output += "</code>"
}
func visitText(node: Text) {
output += escape(text: node.value as! String)
}
func escape(text: String) -> String {
return text.replacingOccurrences(of: "&", with: "&")
.replacingOccurrences(of: "<", with: "<")
.replacingOccurrences(of: ">", with: ">")
.replacingOccurrences(of: "\"", with: """)
}
func visitLineBreak(node: LineBreak) {
if(hardWrap || node.explicit!) {
output += "<br>"
}
output += "\n" + indent()
node.childrenAccept(renderer: self)
}
func escapeUrl(text: String) -> String {
return text
.replacingOccurrences(of: " ", with: "%20")
.replacingOccurrences(of: "\"", with: "%22")
.replacingOccurrences(of: "`", with: "%60")
.replacingOccurrences(of: "<", with: "%3C")
.replacingOccurrences(of: ">", with: "%3E")
.replacingOccurrences(of: "[", with: "%5B")
.replacingOccurrences(of: "]", with: "%5D")
.replacingOccurrences(of: "\\", with: "%5C");
}
func indent() -> String {
var indent = ""
for _ in 0..<(level * 2) {
indent += " "
}
return indent;
}
func getOutput() -> String {
return output.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
|
134656d81bf1c39088ff55f0a11d6304
| 29.315508 | 87 | 0.491445 | false | false | false | false |
superk589/CGSSGuide
|
refs/heads/master
|
DereGuide/Model/Favorite/FavoriteChara.swift
|
mit
|
2
|
//
// FavoriteChara.swift
// DereGuide
//
// Created by zzk on 2017/7/26.
// Copyright © 2017 zzk. All rights reserved.
//
import Foundation
import CoreData
import CloudKit
public class FavoriteChara: NSManagedObject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<FavoriteChara> {
return NSFetchRequest<FavoriteChara>(entityName: "FavoriteChara")
}
@NSManaged public var charaID: Int32
@NSManaged public var createdAt: Date
@NSManaged fileprivate var primitiveCreatedAt: Date
public override func awakeFromInsert() {
super.awakeFromInsert()
primitiveCreatedAt = Date()
}
@discardableResult
static func insert(into moc: NSManagedObjectContext, charaID: Int) -> FavoriteChara {
let favoriteChara: FavoriteChara = moc.insertObject()
favoriteChara.charaID = Int32(charaID)
return favoriteChara
}
}
extension FavoriteChara: Managed {
public static var entityName: String {
return "FavoriteChara"
}
public static var defaultSortDescriptors: [NSSortDescriptor] {
return [NSSortDescriptor(key: #keyPath(FavoriteChara.charaID), ascending: false)]
}
public static var defaultPredicate: NSPredicate {
return notMarkedForDeletionPredicate
}
}
extension FavoriteChara: IDSearchable {
var searchedID: Int {
return Int(charaID)
}
}
extension FavoriteChara: DelayedDeletable {
@NSManaged public var markedForDeletionDate: Date?
}
extension FavoriteChara: RemoteDeletable {
@NSManaged public var markedForRemoteDeletion: Bool
@NSManaged public var remoteIdentifier: String?
}
extension FavoriteChara: UserOwnable {
@NSManaged public var creatorID: String?
}
extension FavoriteChara: RemoteUploadable {
public func toCKRecord() -> CKRecord {
let record = CKRecord(recordType: RemoteFavoriteChara.recordType)
record["charaID"] = charaID as CKRecordValue
record["localCreatedAt"] = createdAt as NSDate
return record
}
}
|
1a58f27a797d2db7a72e4c5ad54df3e5
| 24.728395 | 89 | 0.699616 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
refs/heads/master
|
FirebaseCore/Internal/Sources/HeartbeatLogging/Heartbeat.swift
|
apache-2.0
|
3
|
// Copyright 2021 Google LLC
//
// 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
/// An enumeration of time periods.
enum TimePeriod: Int, CaseIterable, Codable {
/// The raw value is the number of calendar days within each time period.
/// More types can be enabled in future iterations (i.e. `weekly = 7, monthly = 28`).
case daily = 1
/// The number of seconds in a given time period.
var timeInterval: TimeInterval {
Double(rawValue) * 86400 /* seconds in day */
}
}
/// A structure representing SDK usage.
struct Heartbeat: Codable, Equatable {
/// The version of the heartbeat.
private static let version: Int = 0
/// An anonymous string of information (i.e. user agent) to associate the heartbeat with.
let agent: String
/// The date when the heartbeat was recorded.
let date: Date
/// The heartbeat's model version.
let version: Int
/// An array of `TimePeriod`s that the heartbeat is tagged with. See `TimePeriod`.
///
/// Heartbeats represent anonymous data points that measure SDK usage in moving averages for
/// various time periods. Because a single heartbeat can help calculate moving averages for multiple
/// time periods, this property serves to capture all the time periods that the heartbeat can represent in
/// a moving average.
let timePeriods: [TimePeriod]
/// Designated intializer.
/// - Parameters:
/// - agent: An anonymous string of information to associate the heartbeat with.
/// - date: The date when the heartbeat was recorded.
/// - version: The heartbeat's version. Defaults to the current version.
init(agent: String,
date: Date,
timePeriods: [TimePeriod] = [],
version: Int = version) {
self.agent = agent
self.date = date
self.timePeriods = timePeriods
self.version = version
}
}
extension Heartbeat: HeartbeatsPayloadConvertible {
func makeHeartbeatsPayload() -> HeartbeatsPayload {
let userAgentPayloads = [
HeartbeatsPayload.UserAgentPayload(agent: agent, dates: [date]),
]
return HeartbeatsPayload(userAgentPayloads: userAgentPayloads)
}
}
|
0a73db35e3adcdf64931fb3dbf4abdea
| 34.702703 | 108 | 0.713096 | false | false | false | false |
JerrySir/YCOA
|
refs/heads/master
|
YCOA/Main/Apply/Controller/MettingCreatViewController.swift
|
mit
|
1
|
//
// MettingCreatViewController.swift
// YCOA
//
// Created by Jerry on 2016/12/16.
// Copyright © 2016年 com.baochunsteel. All rights reserved.
//
// 会议预定
import UIKit
import MBProgressHUD
import Alamofire
class MettingCreatViewController: UIViewController {
@IBOutlet weak var selectMettingRoomButton: UIButton! //会议室
@IBOutlet weak var selectStartTimeButton: UIButton! //开始时间
@IBOutlet weak var selectEndTimeButton: UIButton! //结束时间
@IBOutlet weak var selectParticipantButton: UIButton! //参会人
@IBOutlet weak var mettingTitleTextField: UITextField! //会议主题
@IBOutlet weak var remindSwitch: UISwitch! //是否提醒
@IBOutlet weak var otherInfoTextView: UITextView! //说明
@IBOutlet weak var submitButton: UIButton! //提交
@IBOutlet weak var backGroundView: UIScrollView! //背景View
//同步服务器的数据
private var mettingRooms: [String] = [] //会议室
//需要提交的
private var selectedMettingRoom: String? //选择的会议室
private var inputedMettingTitle: String? //输入的会议主题
private var selectedStartTime : String? //选择的开始时间
private var selectedEndTime : String? //选择的结束时间
private var isRemind : Bool = false //是否提醒
private var inputedOtherInfo : String? //输入的其他说明
private var participantIDs : [String] = [] //参会人id
private var participantNames : [String] = [] //参会人名
override func viewDidLoad() {
super.viewDidLoad()
self.title = "会议预定"
self.UIConfigure()
self.synchroDataFromServer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Action 绑定
func configureAction() {
//选择会议室
self.selectMettingRoomButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIPickerView.showDidSelectView(SingleColumnDataSource: self.mettingRooms,
onView: self.navigationController!.view,
selectedTap: { (index) in
NSLog("选择了\(index)")
self.selectedMettingRoom = self.mettingRooms[index]
self.selectMettingRoomButton.setTitle(self.selectedMettingRoom, for: .normal)
})
}
//会议主题
self.mettingTitleTextField.rac_textSignal().subscribeNext { (value) in
self.inputedMettingTitle = value as? String
}
//选择开始时间
self.selectStartTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in
self.selectedStartTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00")
self.selectStartTimeButton.setTitle(self.selectedStartTime, for: .normal)
})
}
//选择结束时间
self.selectEndTimeButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.view.endEditing(true)
UIDatePicker.showDidSelectView(minDate: Date(), maxDate: nil, onView: self.navigationController!.view, datePickerMode: .dateAndTime, tap: { (date) in
self.selectedEndTime = (date as NSDate).string(withFormat: "yyyy-MM-dd HH:mm:00")
self.selectEndTimeButton.setTitle(self.selectedEndTime, for: .normal)
})
}
//选择与会人
self.selectParticipantButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
NSLog("选择与会人")
let vc = ContactsSelectTableViewController(style: .plain)
//configure
vc.configure(selectedItems: self.participantIDs, tap: { (ids, names) in
self.participantIDs = ids
self.participantNames = names
self.selectParticipantButton.setTitle("\((names as NSArray).componentsJoined(by: ","))", for: .normal)
})
self.navigationController?.pushViewController(vc, animated: true)
}
//说明
self.otherInfoTextView.rac_textSignal().subscribeNext { (value) in
self.inputedOtherInfo = value as? String
}
//提交
self.submitButton.rac_signal(for: .touchUpInside).subscribeNext { (sender) in
self.didSubmit()
}
//backGroundView
self.backGroundView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer { (sender) in
self.view.endEditing(true)
}
self.backGroundView.addGestureRecognizer(tapGestureRecognizer)
}
//从服务器同步数据
func synchroDataFromServer() {
guard UserCenter.shareInstance().isLogin else {
self.view.jrShow(withTitle: "您未登录")
return
}
//加载中不允许操作
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = .indeterminate
hud.label.text = "初始化中..."
let parameters: Parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!]
guard let url = URL.JRURLEnCoding(string: YCOA_REQUEST_URL.appending("/index.php?d=taskrun&m=meet|appapi&a=getcans&ajaxbool=true")) else {
MBProgressHUD.hide(for: self.view, animated: true)
return
}
Alamofire.request(url, parameters: parameters).responseJSON(completionHandler: { (response) in
MBProgressHUD.hide(for: self.view, animated: true)
guard response.result.isSuccess else{
self.view.jrShow(withTitle: "网络错误")
return
}
guard let returnValue : NSDictionary = response.result.value as? NSDictionary else{
self.view.jrShow(withTitle: "服务器错误")
return
}
guard returnValue.value(forKey: "code") as! Int == 200 else{
self.view.jrShow(withTitle: "\(returnValue.value(forKey: "msg")!)")
return
}
guard let dataArr = returnValue.value(forKey: "data") as? [NSDictionary] else{
self.view.jrShow(withTitle: "暂无数据")
return
}
guard dataArr.count > 0 else{
self.view.jrShow(withTitle: "暂无数据")
return
}
//同步数据
self.mettingRooms = []
for item in dataArr {
guard let roomName = item.value(forKey: "name") as? String else{continue}
self.mettingRooms.append(roomName)
}
//配置Action,只有会议室同步成功才绑定Action
self.configureAction()
})
}
//提交
private func didSubmit() {
guard let hyname: String = self.selectedMettingRoom else{
self.view.jrShow(withTitle: "请选择会议室!")
return
}
guard let title: String = self.inputedMettingTitle else {
self.view.jrShow(withTitle: "请输入会议主题!")
return
}
guard let startdt: String = self.selectedStartTime else {
self.view.jrShow(withTitle: "请输入会议开始时间!")
return
}
guard let enddt: String = self.selectedEndTime else {
self.view.jrShow(withTitle: "请输入会议结束时间!")
return
}
let istz: Int = self.remindSwitch.isOn ? 1 : 0
let joinname: String = (self.participantNames as NSArray).componentsJoined(by: ",")
let joinid: String = (self.participantIDs as NSArray).componentsJoined(by: ",")
let explain: String = self.inputedOtherInfo != nil ? self.inputedOtherInfo! : ""
//发起请求
guard UserCenter.shareInstance().isLogin else {
self.view.jrShow(withTitle: "您未登录")
return
}
//加载中不允许操作
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = .indeterminate
hud.label.text = "提交中..."
let parameters: Parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!,
"hyname": hyname,
"title": title,
"startdt": startdt,
"enddt": enddt,
"istz": istz,
"joinname": joinname,
"joinid": joinid,
"explain": explain]
guard let url = URL.JRURLEnCoding(string: YCOA_REQUEST_URL.appending("/index.php?d=taskrun&m=meet|appapi&a=save&ajaxbool=true")) else {
MBProgressHUD.hide(for: self.view, animated: true)
return
}
Alamofire.request(url, parameters: parameters).responseJSON(completionHandler: { (response) in
MBProgressHUD.hide(for: self.view, animated: true)
guard response.result.isSuccess else{
self.view.jrShow(withTitle: "网络错误")
return
}
guard let returnValue : NSDictionary = response.result.value as? NSDictionary else{
self.view.jrShow(withTitle: "服务器错误")
return
}
guard returnValue.value(forKey: "code") as! Int == 200 else{
self.view.jrShow(withTitle: "\(returnValue.value(forKey: "msg")!)")
return
}
self.view.jrShow(withTitle: "预定会议成功!")
})
}
//MARK: - UI
private func UIConfigure() {
self.makeTextFieldStyle(sender: selectMettingRoomButton)
self.makeTextFieldStyle(sender: selectStartTimeButton)
self.makeTextFieldStyle(sender: selectEndTimeButton)
self.makeTextFieldStyle(sender: selectParticipantButton)
self.makeTextFieldStyle(sender: otherInfoTextView)
self.makeTextFieldStyle(sender: submitButton)
}
///设置控件成为TextField一样的样式
func makeTextFieldStyle(sender: UIView) {
sender.layer.masksToBounds = true
sender.layer.cornerRadius = 10/2
sender.layer.borderWidth = 0.3
sender.layer.borderColor = UIColor.lightGray.cgColor
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
a53c175c7c7d78e01ea6994cc5bcf972
| 38.780822 | 161 | 0.564308 | false | false | false | false |
MHaubenstock/Endless-Dungeon
|
refs/heads/master
|
EndlessDungeon/EndlessDungeon/Container.swift
|
mit
|
1
|
//
// Container.swift
// EndlessDungeon
//
// Created by Michael Haubenstock on 10/7/14.
// Copyright (c) 2014 Michael Haubenstock. All rights reserved.
//
import Foundation
import SpriteKit
class Container : Openable
{
var contents : [Item] = []
//This is maintained from the contents member and is used mostly for organization in views
var contentsDict : [Item.Slot : [Item]] = [:]
var sprite : SKSpriteNode = SKSpriteNode()
var dungeon : Dungeon = Dungeon.sharedInstance
override init()
{
}
init(numOfItems : Int)
{
super.init()
//Add some random items to the container
for i in 0...numOfItems
{
contents.append(Item.randomItem())
}
maintainContentsDict()
}
override func open()
{
dungeon.containerViewController.open(self)
}
override func close()
{
dungeon.containerViewController.close()
}
func addItem(item : Item)
{
contents.append(item)
maintainContentsDict()
}
func removeItem(index : Int) -> Item
{
var itemToRemove : Item = contents.removeAtIndex(index)
maintainContentsDict()
return itemToRemove
}
func maintainContentsDict()
{
contentsDict = [:]
for i in contents
{
if contentsDict[i.slot] == nil
{
contentsDict[i.slot] = []
}
contentsDict[i.slot]?.append(i)
}
}
}
|
91a3ef23ed5870c7dae00271370ef851
| 19.589744 | 94 | 0.542679 | false | false | false | false |
netease-app/NIMSwift
|
refs/heads/master
|
Example/NIMSwift/Common/Circle/CircleImageView.swift
|
mit
|
1
|
//
// CircleImageView.swift
// eval
//
// Created by hengchengfei on 15/9/8.
// Copyright © 2015年 chengfeisoft. All rights reserved.
//
import UIKit
@IBDesignable class CircleImageView: UIImageView {
@IBInspectable var borderWidth:CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius:CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
}
|
1b36209b946a0d90bbf4f71c55da1bd2
| 19.64 | 56 | 0.598837 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Kickstarter-iOS/Features/ProjectPage/Views/Cells/ProjectRisksDisclaimerCell.swift
|
apache-2.0
|
1
|
import KsApi
import Library
import Prelude
import UIKit
protocol ProjectRisksDisclaimerCellDelegate: AnyObject {
func projectRisksDisclaimerCell(_ cell: ProjectRisksDisclaimerCell, didTapURL: URL)
}
final class ProjectRisksDisclaimerCell: UITableViewCell, ValueCell {
// MARK: - Properties
weak var delegate: ProjectRisksDisclaimerCellDelegate?
private let viewModel = ProjectRisksDisclaimerCellViewModel()
private lazy var descriptionLabel: UILabel = { UILabel(frame: .zero) }()
private lazy var rootStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.bindStyles()
self.configureViews()
self.bindViewModel()
let descriptionLabelTapGesture = UITapGestureRecognizer(
target: self,
action: #selector(self.descriptionLabelTapped)
)
self.descriptionLabel.addGestureRecognizer(descriptionLabelTapGesture)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Bindings
override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.notifyDelegateDescriptionLabelTapped
.observeForControllerAction()
.observeValues { [weak self] url in
guard let self = self else { return }
self.delegate?.projectRisksDisclaimerCell(self, didTapURL: url)
}
}
override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> \.separatorInset .~ .init(leftRight: Styles.projectPageLeftRightInset)
_ = self.contentView
|> \.layoutMargins .~
.init(topBottom: Styles.projectPageTopBottomInset, leftRight: Styles.projectPageLeftRightInset)
_ = self.descriptionLabel
|> descriptionLabelStyle
|> \.attributedText .~ self.attributedTextForFootnoteLabel()
_ = self.rootStackView
|> rootStackViewStyle
}
// MARK: - Configuration
func configureWith(value _: Void) {
return
}
private func configureViews() {
_ = (self.rootStackView, self.contentView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
_ = ([self.descriptionLabel], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
}
// MARK: - Helpers
private func attributedTextForFootnoteLabel() -> NSAttributedString {
let attributes: String.Attributes = [
.font: UIFont.ksr_subhead(),
.underlineStyle: NSUnderlineStyle.single.rawValue
]
return NSMutableAttributedString(
string: Strings.Learn_about_accountability_on_Kickstarter(),
attributes: attributes
)
}
// MARK: - Actions
@objc private func descriptionLabelTapped() {
guard let url = HelpType.trust
.url(withBaseUrl: AppEnvironment.current.apiService.serverConfig.webBaseUrl) else { return }
self.viewModel.inputs.descriptionLabelTapped(url: url)
}
}
// MARK: - Styles
private let descriptionLabelStyle: LabelStyle = { label in
label
|> \.adjustsFontForContentSizeCategory .~ true
|> \.isUserInteractionEnabled .~ true
|> \.lineBreakMode .~ .byWordWrapping
|> \.numberOfLines .~ 0
|> \.textColor .~ .ksr_create_700
}
private let rootStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .vertical
|> \.insetsLayoutMarginsFromSafeArea .~ false
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.spacing .~ Styles.grid(3)
}
|
51b5d663dbe63ceb39fbcca09a4554ed
| 26.723077 | 101 | 0.705882 | false | false | false | false |
nebiros/ola-k-ase
|
refs/heads/master
|
OlaKAse/Classes/Controllers/FriendsQueryTableViewController.swift
|
mpl-2.0
|
1
|
//
// MainViewController.swift
// OlaKAse
//
// Created by Juan Felipe Alvarez Saldarriaga on 6/18/15.
// Copyright © 2015 Juan Felipe Alvarez Saldarriaga. All rights reserved.
//
import UIKit
import Parse
import ParseUI
import FBSDKShareKit
class FriendsQueryTableViewController: PFQueryTableViewController {
@IBOutlet weak var addBarButton: UIBarButtonItem!
@IBOutlet weak var loginBarButton: UIBarButtonItem!
@IBOutlet weak var inviteBarButton: UIBarButtonItem!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
parseClassName = Friend.parseClassName()
pullToRefreshEnabled = true
paginationEnabled = true
objectsPerPage = 25;
loadingViewEnabled = false
}
override func viewDidLoad() {
super.viewDidLoad()
setupLoginBarButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated);
guard let currentUser = User.currentUser() else {
return presentLogInVC()
}
let currentInstalation = PFInstallation()
currentInstalation.setObject(currentUser, forKey: "user")
}
// MARK: - PFQueryTableViewController
override func queryForTable() -> PFQuery {
let query = PFQuery(className: parseClassName!)
if pullToRefreshEnabled {
query.cachePolicy = .NetworkOnly
}
if objects?.count == 0 {
query.cachePolicy = .CacheElseNetwork
}
return query
}
}
// MARK: - UI
extension FriendsQueryTableViewController {
func presentLogInVC() {
let loginVC = PFLogInViewController()
loginVC.delegate = self
loginVC.fields = [.Default, .Facebook]
loginVC.facebookPermissions = ["public_profile", "email", "user_friends"]
presentViewController(loginVC, animated: true, completion: nil)
}
@IBAction func addBarButtonTapped(sender: UIBarButtonItem) {
}
func setupLoginBarButtonItem() {
guard let _ = User.currentUser() else {
loginBarButton.title = NSLocalizedString("Login", comment: "")
return
}
loginBarButton.title = NSLocalizedString("Logout", comment: "")
}
@IBAction func loginBarButtonTapped(sender: UIBarButtonItem) {
guard let _ = User.currentUser() else {
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLoginBarButtonItem"), userInfo: nil, repeats: false)
return presentLogInVC()
}
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLoginBarButtonItem"), userInfo: nil, repeats: false)
User.logOutInBackground()
}
@IBAction func inviteBarButtonTapped(sender: UIBarButtonItem) {
presentFacebookAppInviteDialog()
}
}
// MARK: - FBSDKAppInviteDialogDelegate
extension FriendsQueryTableViewController: FBSDKAppInviteDialogDelegate {
func presentFacebookAppInviteDialog() {
let content = FBSDKAppInviteContent()
content.appLinkURL = NSURL(string: "https://fb.me/1601337420135347")
FBSDKAppInviteDialog.showWithContent(content, delegate: self)
}
func appInviteDialog(appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [NSObject : AnyObject]!) {
}
func appInviteDialog(appInviteDialog: FBSDKAppInviteDialog!, didFailWithError error: NSError!) {
}
}
// MARK: - PFLogInViewControllerDelegate
extension FriendsQueryTableViewController: PFLogInViewControllerDelegate {
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLoginBarButtonItem"), userInfo: nil, repeats: false)
logInController.dismissViewControllerAnimated(true, completion: nil)
}
}
|
a1edf97364d812542bec69c5c4ec5e58
| 28.895833 | 147 | 0.660859 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift
|
refs/heads/master
|
Solutions/Solutions/Hard/Hard_076_Minimum_Window_Substring.swift
|
mit
|
3
|
/*
https://leetcode.com/problems/minimum-window-substring/
#76 Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Inspired by @heleifz at https://leetcode.com/discuss/10337/accepted-o-n-solution
*/
import Foundation
private extension String {
subscript (index: Int) -> Character {
return self[self.startIndex.advancedBy(index)]
}
}
struct Hard_076_Minimum_Window_Substring {
static func minWindow(s s: String, t: String) -> String {
if s.isEmpty || t.isEmpty {
return ""
}
var count = t.characters.count
var charCountDict: Dictionary<Character, Int> = Dictionary()
var charFlagDict: Dictionary<Character, Bool> = Dictionary()
for var ii = 0; ii < count; ii++ {
if let charCount = charCountDict[t[ii]] {
charCountDict[t[ii]] = charCount + 1
} else {
charCountDict[t[ii]] = 1
}
charFlagDict[t[ii]] = true
}
var i = -1
var j = 0
var minLen = Int.max
var minIdx = 0
while i < s.characters.count && j < s.characters.count {
if count > 0 {
i++
if i == s.characters.count {
continue
}
if let charCount = charCountDict[s[i]] {
charCountDict[s[i]] = charCount - 1
} else {
charCountDict[s[i]] = -1
}
if charFlagDict[s[i]] == true && charCountDict[s[i]] >= 0 {
count--
}
} else {
if minLen > i - j + 1 {
minLen = i - j + 1
minIdx = j
}
if let charCount = charCountDict[s[j]] {
charCountDict[s[j]] = charCount + 1
} else {
charCountDict[s[j]] = 1
}
if charFlagDict[s[j]] == true && charCountDict[s[j]] > 0 {
count++
}
j++
}
}
if minLen == Int.max {
return ""
}
let range = Range<String.Index>(start: s.startIndex.advancedBy(minIdx), end: s.startIndex.advancedBy(minIdx + minLen))
return s.substringWithRange(range)
}
}
|
493a1cc797a71d58a21d5028b30641e9
| 30.494253 | 126 | 0.51004 | false | false | false | false |
digoreis/swift-proposal-analyzer
|
refs/heads/master
|
swift-proposal-analyzer.playground/Pages/SE-0151.xcplaygroundpage/Contents.swift
|
mit
|
2
|
/*:
# Package Manager Swift Language Compatibility Version
* Proposal: [SE-0151](0151-package-manager-swift-language-compatibility-version.md)
* Authors: [Daniel Dunbar](https://github.com/ddunbar), [Rick Ballard](http://github.com/rballard)
* Review Manager: [Anders Bertelrud](https://github.com/abertelrud)
* Status: **Implemented (Swift 3.1)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170213/032021.html)
* Bug: [SR-3964](https://bugs.swift.org/browse/SR-3964)
## Introduction
This proposal adds support for the Swift compiler's new "language compatibility
version" feature to the package manager.
## Motivation
The Swift compiler now supports a "language compatibility version" flag which
specifies the Swift major language version that the compiler should try to
accept. We need support for an additional package manager manifest feature in
order for this feature to be used by Swift packages.
## Proposed solution
We will add support to the package manifest declaration to specify a set of
supported Swift language versions:
```swift
let package = Package(
name: "HTTP",
...
swiftLanguageVersions: [3, 4])
```
When building a package, we will always select the Swift language version that
is most close to (but not exceeding) the major version of the Swift compiler in
use.
If a package does not support any version compatible with the current compiler,
we will report an error.
If a package does not specify any Swift language versions, the
language version to be used will match the major version of the the
package's Swift tools version (as discussed in a separate evolution proposal). A
Swift tools version with a major version of '3' will imply a default Swift
language version of '3', and a Swift tools version with a major version
of '4' will imply a default Swift language version of '4'.
## Detailed design
We are operating under the assumption that for the immediate future, the Swift
language compatibility version accepted by the compiler will remain an integer
major version.
With this change, the complete package initializer will be:
```swift
public init(
name: String,
pkgConfig: String? = nil,
providers: [SystemPackageProvider]? = nil,
targets: [Target] = [],
products: [Product] = [],
dependencies: [Dependency] = [],
swiftLanguageVersions: [Int]? = nil,
exclude: [String] = []
```
where absence of the optional language version list indicates the default
behavior should be used for this package.
### Example Behaviors
Here are concrete examples of how the package manager will compile code,
depending on its language version declarations:
* Version 3 Packager Manager & Swift 3 (only) Language Package
The package manager will compile the code with `-swift-version 3`.
* Version 3 Packager Manager & Swift 4 (only) Language Package
The package manager will report an error, since the package supports no language
version compatible with the tools.
* Version 3 Packager Manager & Swift [3, 4] Language Package
The package manager will compile the code with `-swift-version 3`, matching the
major version of the tools in use.
* Version 4 Packager Manager & Swift 3 (only) Language Package
The package manager will compile the code with `-swift-version 3`.
* Version 4 Packager Manager & Swift 4 (only) Language Package
The package manager will compile the code with `-swift-version 4`.
* Version 4 Packager Manager & Swift [3, 4] Language Package
The package manager will compile the code with `-swift-version 4`.
Clients wishing to validate actual Swift 3 compatibility are expected to do so
by using an actual Swift 3 implementation to build, since the Swift compiler
does not commit to maintaining pedantic Swift 3 compatibility (that is, it is
designed to *accept* any valid Swift 3 code in the `-swift-version 3`
compatibility mode, but not necessarily to *reject* any code which the Swift 3
compiler would not have accepted).
## Impact on existing code
Since this is a new API, all packages will use the default behavior once
implemented. Because the default Swift tools version of existing packages
is "3.0.0" (pending approval of the Swift tools version proposal), the Swift
4 package manager will build such packages in Swift 3 mode. When packages
wish to migrate to the Swift 4 language, they can either update their
Swift tools version or specify Swift 4 as their language version.
New packages created with `swift package init` by the Swift 4 tools will
build with the Swift 4 language by default, due to the Swift tools version
that `swift package init` chooses.
This is a new manifest API, so packages which adopt this API will no longer be
buildable with package manager versions which do not recognize that
API. We expect to add support for this API to Swift 3.1, so it will be possible
to create packages which support the Swift 4 and 3 languages and the Swift
4 and 3.1 tools.
## Alternatives considered
We could have made the Swift language version default to the version of the
Swift tools in use if not specified. However, tying this to the Swift tools
version instead allows existing Swift 3 language packages to build with the
Swift 4 tools without changes, as they won't need to explicitly specify a Swift
language version in order to continue to build with the Swift 3 language.
We chose not to support any command line features to modify the selected version
(e.g., to force a Swift 4 compiler to use Swift 3 mode where acceptable) in
order to keep this proposal simple. We will consider these in the future if they
prove necessary.
We considered supporting a way to set the Swift language version on
a per-module basis, instead of needing to set it for the entire package.
We think this would be best done using build settings, which the package
manager does not yet support. We are pending per-module support for this
feature until build settings are supported.
----------
[Previous](@previous) | [Next](@next)
*/
|
1ac151c45f5b0314528f4f185b46f4e8
| 38.940789 | 113 | 0.764948 | false | false | false | false |
naokits/my-programming-marathon
|
refs/heads/master
|
Bluemix/StrongLoopDemo/StrongLoopClientDemo/StrongLoopClientDemo/Models/Login.swift
|
mit
|
1
|
//
// Login.swift
// StrongLoopClientDemo
//
// Created by Naoki Tsutsui on 5/14/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import APIKit
struct Login {
var token: String?
var ttl: Int?
var created: String?
var userId: Int?
/*
"id": "XsTaFzM5wpdSQmi7EIXe71gNvitPeoHRrA7HDTuFJMEe0yQ9pmi2KATIMjy7rry6",
"ttl": 1209600,
"created": "2016-05-14T02:01:41.270Z",
"userId": 1
*/
init?(dic: [String: AnyObject]) {
guard let token = dic["id"] as? String else {
return nil
}
guard let ttl = dic["ttl"] as? Int else {
return nil
}
guard let created = dic["created"] as? String else {
return nil
}
guard let userId = dic["userId"] as? Int else {
return nil
}
self.token = token
self.ttl = ttl
self.created = created
self.userId = userId
}
}
protocol LoginRequestType: RequestType {
}
extension LoginRequestType {
var baseURL: NSURL {
return NSURL(string: demoBaseURL)!
}
}
struct LoginRequest: LoginRequestType {
typealias Response = Login
var method: HTTPMethod {
return .POST
}
var path: String {
return "/api/DemoUsers/login"
}
var email: String = ""
var password: String = ""
var parameters: [String: AnyObject] {
let body = [
"email": self.email,
"password": self.password,
]
return body
}
init(email: String, password: String) {
self.email = email
self.password = password
}
func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
guard let dictionary = object as? [String: AnyObject] else {
return nil
}
guard let result = Login(dic: dictionary) else {
return nil
}
return result
}
}
struct LogoutRequest: LoginRequestType {
typealias Response = Login
var method: HTTPMethod {
return .POST
}
var path: String {
return "/api/DemoUsers/logout"
}
var accessToken: String = ""
var parameters: [String: AnyObject] {
return [
"access_token":self.accessToken,
]
}
init(accessToken: String) {
self.accessToken = accessToken
}
func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
print(object)
guard let dictionary = object as? [String: AnyObject] else {
return nil
}
guard let result = Login(dic: dictionary) else {
return nil
}
return result
}
}
|
152006358f5357e825c4eb0eef31b47a
| 20.526718 | 93 | 0.549645 | false | false | false | false |
astralbodies/TaterTotTimerRxSwift
|
refs/heads/master
|
TaterTotTimer/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// TaterTotTimer
//
// Created by Aaron Douglas on 10/5/15.
// Copyright © 2015 Automattic. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class ViewController: UIViewController {
@IBOutlet var totCountLabel: UILabel!
@IBOutlet var totCountStepper: UIStepper!
@IBOutlet var totImage: UIImageView!
@IBOutlet var startStopButton: UIButton!
@IBOutlet var timerFace: UILabel!
let disposeBag = DisposeBag()
var totalNumberOfTots = Variable(5)
var timerRunning = Variable(false)
var targetDate: NSDate?
var degrees = 0.0
override func viewDidLoad() {
super.viewDidLoad()
let timerIsNotRunning = timerRunning
.asObservable()
.map({timerRunning in !timerRunning})
.shareReplay(1)
totalNumberOfTots
.asObservable()
.subscribeNext { tots in
self.totCountLabel.text = "Number of Tots: \(tots)"
}
.addDisposableTo(disposeBag)
totCountStepper
.rx_value
.subscribeNext { value in
self.totalNumberOfTots.value = Int(value)
}
.addDisposableTo(disposeBag)
startStopButton
.rx_tap
.subscribeNext {
self.timerRunning.value = !self.timerRunning.value
}
.addDisposableTo(disposeBag)
timerIsNotRunning
.bindTo(timerFace.rx_hidden)
.addDisposableTo(disposeBag)
timerRunning
.asObservable()
.bindTo(totCountStepper.rx_hidden)
.addDisposableTo(disposeBag)
timerRunning
.asObservable()
.bindTo(totCountLabel.rx_hidden)
.addDisposableTo(disposeBag)
timerRunning
.asObservable()
.map { $0 ? "Stop Timer" : "Start Timer" }
.bindTo(startStopButton.rx_title(.Normal))
.addDisposableTo(disposeBag)
timerIsNotRunning
.subscribeNext { value in
self.targetDate = nil
self.cancelLocalNotifications()
self.totImage.transform = CGAffineTransformIdentity
self.degrees = 0.0
}
.addDisposableTo(disposeBag)
Observable<Int>
.timer(0.0, period: 0.1, scheduler: MainScheduler.instance)
.pausable(timerRunning.asObservable())
.subscribeNext({ seconds in
self.refreshTotAndTimer()
})
.addDisposableTo(self.disposeBag)
timerRunning
.asObservable()
.filter {
$0 == true
}
.subscribeNext { value in
let dateComponents = NSDateComponents.init()
let calendar = NSCalendar.currentCalendar()
dateComponents.second = self.timeForNumberOfTots(self.totalNumberOfTots.value)
self.targetDate = calendar.dateByAddingComponents(dateComponents, toDate: NSDate.init(), options: [])
self.scheduleLocalNotification(self.targetDate!)
}
.addDisposableTo(disposeBag)
}
func refreshTotAndTimer() {
let calendar = NSCalendar.currentCalendar()
let dateComponents = calendar.components([.Minute, .Second], fromDate: NSDate(), toDate: targetDate!, options: [])
guard targetDate!.timeIntervalSinceReferenceDate > NSDate().timeIntervalSinceReferenceDate else {
self.timerRunning.value = false
return
}
degrees += 20
totImage.transform = CGAffineTransformMakeRotation(CGFloat(degrees * M_PI/180))
let dateDiff = calendar.dateFromComponents(dateComponents)!
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "mm:ss"
let formattedTime = dateFormatter.stringFromDate(dateDiff)
timerFace.text = formattedTime
}
func timeForNumberOfTots(numberOfTots:Int) -> Int {
if (numberOfTots > 0 && numberOfTots <= 20) {
return 22 * 60
} else if (numberOfTots <= 30) {
return 24 * 60
} else {
return 26 * 60
}
}
func scheduleLocalNotification(targetDate: NSDate) {
let localNotification = UILocalNotification()
localNotification.fireDate = targetDate
localNotification.alertTitle = "Tater Tot Timer"
localNotification.alertBody = "Your tots are done!"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
func cancelLocalNotifications() {
UIApplication.sharedApplication().cancelAllLocalNotifications()
}
}
|
2123c48c1c461f35c47b2e0085306d42
| 30.506329 | 122 | 0.585777 | false | false | false | false |
Tj3n/TVNExtensions
|
refs/heads/master
|
UIKit/AVAudioSession.swift
|
mit
|
1
|
//
// AVAudioSession+Extension.swift
// TVNExtensions
//
// Created by Tien Nhat Vu on 2/2/18.
//
import Foundation
import AVFoundation
extension AVAudioSession {
public static var isHeadphonesConnected: Bool {
return sharedInstance().isHeadphonesConnected
}
public var isHeadphonesConnected: Bool {
return !currentRoute.outputs.filter { $0.isHeadphones }.isEmpty
}
//No way to do for lower iOS, have to use Obj-C
@available(iOS 10.0, *)
public class func mixWithBackgroundMusic() {
_ = try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
}
}
extension AVAudioSessionPortDescription {
public var isHeadphones: Bool {
return portType == .headphones
}
}
public class AudioDetection {
var callback: ((_ isConnected: Bool)->())?
public init(callback: @escaping ((_ isConnected: Bool)->())) {
self.callback = callback;
self.listenForNotifications()
}
deinit {
callback = nil
NotificationCenter.default.removeObserver(self)
}
func listenForNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: AVAudioSession.routeChangeNotification, object: nil)
}
@objc func handleRouteChange(_ notification: Notification) {
guard
let userInfo = notification.userInfo,
let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonRaw.uintValue)
else { fatalError("Strange... could not get routeChange") }
switch reason {
case .oldDeviceUnavailable:
callback?(false)
case .newDeviceAvailable:
print("newDeviceAvailable")
if AVAudioSession.isHeadphonesConnected {
callback?(true)
}
case .routeConfigurationChange:
print("routeConfigurationChange")
case .categoryChange:
print("categoryChange")
default:
print("not handling reason")
}
}
}
|
8b094cb2ad58f632cbc0b36d41ec62cf
| 29.5 | 155 | 0.643443 | false | false | false | false |
MenloHacks/ios-app
|
refs/heads/master
|
Menlo Hacks/Pods/PusherSwift/Sources/PusherGlobalChannel.swift
|
mit
|
1
|
import Foundation
@objcMembers
@objc open class GlobalChannel: PusherChannel {
open var globalCallbacks: [String : (Any?) -> Void] = [:]
/**
Initializes a new GlobalChannel instance
- parameter connection: The connection associated with the global channel
- returns: A new GlobalChannel instance
*/
init(connection: PusherConnection) {
super.init(name: "pusher_global_internal_channel", connection: connection)
}
/**
Calls the appropriate callbacks for the given event name in the scope of the global channel
- parameter name: The name of the received event
- parameter data: The data associated with the received message
- parameter channelName: The name of the channel that the received message was triggered
to, if relevant
*/
internal func handleEvent(name: String, data: String, channelName: String?) {
for (_, callback) in self.globalCallbacks {
if let channelName = channelName {
callback(["channel": channelName, "event": name, "data": data] as [String: Any])
} else {
callback(["event": name, "data": data] as [String: Any])
}
}
}
/**
Calls the appropriate callbacks for the given event name in the scope of the global channel
- parameter name: The name of the received event
- parameter data: The data associated with the received message
*/
internal func handleErrorEvent(name: String, data: [String: AnyObject]) {
for (_, callback) in self.globalCallbacks {
callback(["event": name, "data": data])
}
}
/**
Binds a callback to the global channel
- parameter callback: The function to call when a message is received
- returns: A unique callbackId that can be used to unbind the callback at a later time
*/
internal func bind(_ callback: @escaping (Any?) -> Void) -> String {
let randomId = UUID().uuidString
self.globalCallbacks[randomId] = callback
return randomId
}
/**
Unbinds the callback with the given callbackId from the global channel
- parameter callbackId: The unique callbackId string used to identify which callback to unbind
*/
internal func unbind(callbackId: String) {
globalCallbacks.removeValue(forKey: callbackId)
}
/**
Unbinds all callbacks from the channel
*/
override open func unbindAll() {
globalCallbacks = [:]
}
}
|
75acc7067c00fa4d2b9f7644686f3410
| 33.210526 | 102 | 0.626154 | false | false | false | false |
509dave16/udemy_swift_ios_projects
|
refs/heads/master
|
playground/Conditionals.playground/Contents.swift
|
gpl-2.0
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var isMyHouseOnFire : Bool = false;
var anotherBool = true;
if isMyHouseOnFire {
print("Someone get me some water!");
} else {
print("Someone get some fire for my house!");
}
var result = true == true;
result = true == false;
result = false == false;
var accountTotal = 40.33;
var newCallOfDutyGame = 59.99;
if(accountTotal >= newCallOfDutyGame) {
print("I just purchased the game!");
} else {
print("I don't have enough money!");
}
var name = "Jacky";
if name == "Jack" {
print("Your name is Jack!");
} else {
print("Your name is not Jack!");
}
var numberA = 25;
var numberB = 40;
var numberC = 45;
var numberD = 50;
var finalNumber = 100;
if numberA == finalNumber {
print(numberA);
} else if numberB == finalNumber {
print(numberB);
} else if numberC == finalNumber {
print(numberC);
} else {
print("None of the values were equal to finalNumber");
}
|
c1cfb322537f090a30d39a81dfcebf99
| 18.039216 | 58 | 0.652577 | false | false | false | false |
smilelu/SSLNavigationBar
|
refs/heads/master
|
Example/SSLNavigationBar/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SSLNavigationBar
//
// Created by smilelu on 08/23/2016.
// Copyright (c) 2016 smilelu. All rights reserved.
//
import UIKit
import SSLNavigationBar
class ViewController: SLBaseViewController {
var nextBtn:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "SSLNavigationBar Demo"
nextBtn = UIButton()
nextBtn.setTitle("NextViewController", for: UIControl.State())
nextBtn.setTitleColor(UIColor.blue, for: UIControl.State())
nextBtn.addTarget(self, action: #selector(nextAction(_:)), for: UIControl.Event.touchUpInside)
self.view.insertSubview(nextBtn, belowSubview: self.naviBar)
self.setLayout()
}
func setLayout() -> Void {
nextBtn.snp_makeConstraints { (make) in
make.center.equalTo(self.view)
}
}
override func initNaviBar() -> Void {
super.initNaviBar()
let leftItem : SLBarButtonItem = SLBarButtonItem(image: UIImage(named: "titlebar_user"), target: self, action: #selector(userClick(_:)))
self.naviBar.leftItem = leftItem
}
@objc func userClick(_ sender: SLBarButtonItem) -> Void {
NSLog("LeftBarButtonItem Click!")
}
@objc func nextAction(_ sender: UIButton) -> Void {
let nextVC:NextViewController = NextViewController()
self.navigationController?.pushViewController(nextVC, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
1a7ae4a0fffef2b1ef9a5ec9fecb41f9
| 26.810345 | 144 | 0.636702 | false | false | false | false |
nuan-nuan/Socket.IO-Client-Swift
|
refs/heads/master
|
SocketIO-iOSTests/SocketParserTest.swift
|
apache-2.0
|
1
|
//
// SocketParserTest.swift
// Socket.IO-Client-Swift
//
// Created by Lukas Schmidt on 05.09.15.
//
//
import XCTest
class SocketParserTest: XCTestCase {
//Format key: message; namespace-data-binary-id
static let packetTypes: Dictionary<String, (String, [AnyObject], [NSData], Int)> = [
"0": ("/", [], [], -1), "1": ("/", [], [], -1),
"25[\"test\"]": ("/", ["test"], [], 5),
"2[\"test\",\"~~0\"]": ("/", ["test", "~~0"], [], -1),
"2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]": ("/swift", ["testArrayEmitReturn", ["test3", "test4"]], [], -1),
"51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", ["testMultipleItemsWithBufferEmitReturn", [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], -1),
"3/swift,0[[\"test3\",\"test4\"]]": ("/swift", [["test3", "test4"]], [], 0),
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], 19),
"4/swift,": ("/swift", [], [], -1),
"0/swift": ("/swift", [], [], -1),
"1/swift": ("/swift", [], [], -1),
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
"41": ("/", [1], [], -1)]
func testDisconnect() {
let message = "1"
validateParseResult(message)
}
func testConnect() {
let message = "0"
validateParseResult(message)
}
func testDisconnectNameSpace() {
let message = "1/swift"
validateParseResult(message)
}
func testConnecttNameSpace() {
let message = "0/swift"
validateParseResult(message)
}
func testIdEvent() {
let message = "25[\"test\"]"
validateParseResult(message)
}
func testBinaryPlaceholderAsString() {
let message = "2[\"test\",\"~~0\"]"
validateParseResult(message)
}
func testNameSpaceArrayParse() {
let message = "2/swift,[\"testArrayEmitReturn\",[\"test3\",\"test4\"]]"
validateParseResult(message)
}
func testNameSpaceArrayAckParse() {
let message = "3/swift,0[[\"test3\",\"test4\"]]"
validateParseResult(message)
}
func testNameSpaceBinaryEventParse() {
let message = "51-/swift,[\"testMultipleItemsWithBufferEmitReturn\",[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]"
validateParseResult(message)
}
func testNameSpaceBinaryAckParse() {
let message = "61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]"
validateParseResult(message)
}
func testNamespaceErrorParse() {
let message = "4/swift,"
validateParseResult(message)
}
func testErrorTypeString() {
let message = "4\"ERROR\""
validateParseResult(message)
}
func testErrorTypeInt() {
let message = "41"
validateParseResult(message)
}
func testInvalidInput() {
let message = "8"
switch SocketParser.parseString(message) {
case .Left(_):
return
case .Right(_):
XCTFail("Created packet when shouldn't have")
}
}
func testGenericParser() {
var parser = SocketStringReader(message: "61-/swift,")
XCTAssertEqual(parser.read(1), "6")
XCTAssertEqual(parser.currentCharacter, "1")
XCTAssertEqual(parser.readUntilStringOccurence("-"), "1")
XCTAssertEqual(parser.currentCharacter, "/")
}
func validateParseResult(message: String) {
let validValues = SocketParserTest.packetTypes[message]!
let packet = SocketParser.parseString(message)
let type = message.substringWithRange(Range<String.Index>(start: message.startIndex, end: message.startIndex.advancedBy(1)))
if case let .Right(packet) = packet {
XCTAssertEqual(packet.type, SocketPacket.PacketType(rawValue: Int(type) ?? -1)!)
XCTAssertEqual(packet.nsp, validValues.0)
XCTAssertTrue((packet.data as NSArray).isEqualToArray(validValues.1))
XCTAssertTrue((packet.binary as NSArray).isEqualToArray(validValues.2))
XCTAssertEqual(packet.id, validValues.3)
} else {
XCTFail()
}
}
func testParsePerformance() {
let keys = Array(SocketParserTest.packetTypes.keys)
measureBlock({
for item in keys.enumerate() {
SocketParser.parseString(item.element)
}
})
}
}
|
8a8efca7794ed912ffdeb71df1b22a58
| 33.843284 | 242 | 0.551724 | false | true | false | false |
Onetaway/iOS8-day-by-day
|
refs/heads/master
|
19-core-image-kernels/FilterBuilder/FilterBuilder/SobelViewController.swift
|
apache-2.0
|
3
|
//
// Copyright 2014 Scott Logic
//
// 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 UIKit
class SobelViewController: UIViewController {
// MARK: - Properties
let filter = SobelFilter()
// MARK: - IBOutlets
@IBOutlet weak var outputImageView: UIImageView!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupFilter()
updateOutputImage()
}
// MARK: - Utility methods
private func updateOutputImage() {
outputImageView.image = filteredImage()
}
private func filteredImage() -> UIImage {
let outputImage = filter.outputImage
return UIImage(CIImage: outputImage)
}
private func setupFilter() {
// Need an input image
let inputImage = UIImage(named: "flowers")
filter.inputImage = CIImage(image: inputImage)
}
}
|
c251957d348637cd955ed382b776ba1e
| 26.076923 | 76 | 0.705966 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
iOS/Article/ArticleViewController.swift
|
mit
|
1
|
//
// ArticleViewController.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import WebKit
import Account
import Articles
import SafariServices
class ArticleViewController: UIViewController {
typealias State = (extractedArticle: ExtractedArticle?,
isShowingExtractedArticle: Bool,
articleExtractorButtonState: ArticleExtractorButtonState,
windowScrollY: Int)
@IBOutlet private weak var nextUnreadBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var prevArticleBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var nextArticleBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var readBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var starBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var actionBarButtonItem: UIBarButtonItem!
@IBOutlet private var searchBar: ArticleSearchBar!
@IBOutlet private var searchBarBottomConstraint: NSLayoutConstraint!
private var defaultControls: [UIBarButtonItem]?
private var pageViewController: UIPageViewController!
private var currentWebViewController: WebViewController? {
return pageViewController?.viewControllers?.first as? WebViewController
}
private var articleExtractorButton: ArticleExtractorButton = {
let button = ArticleExtractorButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 44.0, height: 44.0)
button.setImage(AppAssets.articleExtractorOff, for: .normal)
return button
}()
weak var coordinator: SceneCoordinator!
var article: Article? {
didSet {
if let controller = currentWebViewController, controller.article != article {
controller.setArticle(article)
DispatchQueue.main.async {
// You have to set the view controller to clear out the UIPageViewController child controller cache.
// You also have to do it in an async call or you will get a strange assertion error.
self.pageViewController.setViewControllers([controller], direction: .forward, animated: false, completion: nil)
}
}
updateUI()
}
}
var restoreScrollPosition: (isShowingExtractedArticle: Bool, articleWindowScrollY: Int)? {
didSet {
if let rsp = restoreScrollPosition {
currentWebViewController?.setScrollPosition(isShowingExtractedArticle: rsp.isShowingExtractedArticle, articleWindowScrollY: rsp.articleWindowScrollY)
}
}
}
var currentState: State? {
guard let controller = currentWebViewController else { return nil}
return State(extractedArticle: controller.extractedArticle,
isShowingExtractedArticle: controller.isShowingExtractedArticle,
articleExtractorButtonState: controller.articleExtractorButtonState,
windowScrollY: controller.windowScrollY)
}
var restoreState: State?
private let keyboardManager = KeyboardManager(type: .detail)
override var keyCommands: [UIKeyCommand]? {
return keyboardManager.keyCommands
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
let fullScreenTapZone = UIView()
NSLayoutConstraint.activate([
fullScreenTapZone.widthAnchor.constraint(equalToConstant: 150),
fullScreenTapZone.heightAnchor.constraint(equalToConstant: 44)
])
fullScreenTapZone.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapNavigationBar)))
navigationItem.titleView = fullScreenTapZone
articleExtractorButton.addTarget(self, action: #selector(toggleArticleExtractor(_:)), for: .touchUpInside)
toolbarItems?.insert(UIBarButtonItem(customView: articleExtractorButton), at: 6)
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [:])
pageViewController.delegate = self
pageViewController.dataSource = self
// This code is to disallow paging if we scroll from the left edge. If this code is removed
// PoppableGestureRecognizerDelegate will allow us to both navigate back and page back at the
// same time. That is really weird when it happens.
let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.delegate = self
pageViewController.scrollViewInsidePageControl?.addGestureRecognizer(panGestureRecognizer)
pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pageViewController.view)
addChild(pageViewController!)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: pageViewController.view.leadingAnchor),
view.trailingAnchor.constraint(equalTo: pageViewController.view.trailingAnchor),
view.topAnchor.constraint(equalTo: pageViewController.view.topAnchor),
view.bottomAnchor.constraint(equalTo: pageViewController.view.bottomAnchor)
])
let controller: WebViewController
if let state = restoreState {
controller = createWebViewController(article, updateView: false)
controller.extractedArticle = state.extractedArticle
controller.isShowingExtractedArticle = state.isShowingExtractedArticle
controller.articleExtractorButtonState = state.articleExtractorButtonState
controller.windowScrollY = state.windowScrollY
} else {
controller = createWebViewController(article, updateView: true)
}
if let rsp = restoreScrollPosition {
controller.setScrollPosition(isShowingExtractedArticle: rsp.isShowingExtractedArticle, articleWindowScrollY: rsp.articleWindowScrollY)
}
articleExtractorButton.buttonState = controller.articleExtractorButtonState
self.pageViewController.setViewControllers([controller], direction: .forward, animated: false, completion: nil)
if AppDefaults.shared.articleFullscreenEnabled {
controller.hideBars()
}
// Search bar
searchBar.translatesAutoresizingMaskIntoConstraints = false
NotificationCenter.default.addObserver(self, selector: #selector(beginFind(_:)), name: .FindInArticle, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(endFind(_:)), name: .EndFindInArticle, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIWindow.keyboardWillChangeFrameNotification, object: nil)
searchBar.delegate = self
view.bringSubviewToFront(searchBar)
updateUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
coordinator.isArticleViewControllerPending = false
}
override func viewWillDisappear(_ animated: Bool) {
if searchBar != nil && !searchBar.isHidden {
endFind()
}
}
override func viewSafeAreaInsetsDidChange() {
// This will animate if the show/hide bars animation is happening.
view.layoutIfNeeded()
}
func updateUI() {
guard let article = article else {
articleExtractorButton.isEnabled = false
nextUnreadBarButtonItem.isEnabled = false
prevArticleBarButtonItem.isEnabled = false
nextArticleBarButtonItem.isEnabled = false
readBarButtonItem.isEnabled = false
starBarButtonItem.isEnabled = false
actionBarButtonItem.isEnabled = false
return
}
nextUnreadBarButtonItem.isEnabled = coordinator.isAnyUnreadAvailable
prevArticleBarButtonItem.isEnabled = coordinator.isPrevArticleAvailable
nextArticleBarButtonItem.isEnabled = coordinator.isNextArticleAvailable
readBarButtonItem.isEnabled = true
starBarButtonItem.isEnabled = true
let permalinkPresent = article.preferredLink != nil
var isFeedProvider = false
if let webfeed = article.webFeed {
isFeedProvider = webfeed.isFeedProvider
}
articleExtractorButton.isEnabled = permalinkPresent && !AppDefaults.shared.isDeveloperBuild && !isFeedProvider
actionBarButtonItem.isEnabled = permalinkPresent
if article.status.read {
readBarButtonItem.image = AppAssets.circleOpenImage
readBarButtonItem.isEnabled = article.isAvailableToMarkUnread
readBarButtonItem.accLabelText = NSLocalizedString("Mark Article Unread", comment: "Mark Article Unread")
} else {
readBarButtonItem.image = AppAssets.circleClosedImage
readBarButtonItem.isEnabled = true
readBarButtonItem.accLabelText = NSLocalizedString("Selected - Mark Article Unread", comment: "Selected - Mark Article Unread")
}
if article.status.starred {
starBarButtonItem.image = AppAssets.starClosedImage
starBarButtonItem.accLabelText = NSLocalizedString("Selected - Star Article", comment: "Selected - Star Article")
} else {
starBarButtonItem.image = AppAssets.starOpenImage
starBarButtonItem.accLabelText = NSLocalizedString("Star Article", comment: "Star Article")
}
}
// MARK: Notifications
@objc dynamic func unreadCountDidChange(_ notification: Notification) {
updateUI()
}
@objc func statusesDidChange(_ note: Notification) {
guard let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String> else {
return
}
guard let article = article else {
return
}
if articleIDs.contains(article.articleID) {
updateUI()
}
}
@objc func contentSizeCategoryDidChange(_ note: Notification) {
currentWebViewController?.fullReload()
}
@objc func willEnterForeground(_ note: Notification) {
// The toolbar will come back on you if you don't hide it again
if AppDefaults.shared.articleFullscreenEnabled {
currentWebViewController?.hideBars()
}
}
// MARK: Actions
@objc func didTapNavigationBar() {
currentWebViewController?.hideBars()
}
@objc func showBars(_ sender: Any) {
currentWebViewController?.showBars()
}
@IBAction func toggleArticleExtractor(_ sender: Any) {
currentWebViewController?.toggleArticleExtractor()
}
@IBAction func nextUnread(_ sender: Any) {
coordinator.selectNextUnread()
}
@IBAction func prevArticle(_ sender: Any) {
coordinator.selectPrevArticle()
}
@IBAction func nextArticle(_ sender: Any) {
coordinator.selectNextArticle()
}
@IBAction func toggleRead(_ sender: Any) {
coordinator.toggleReadForCurrentArticle()
}
@IBAction func toggleStar(_ sender: Any) {
coordinator.toggleStarredForCurrentArticle()
}
@IBAction func showActivityDialog(_ sender: Any) {
currentWebViewController?.showActivityDialog(popOverBarButtonItem: actionBarButtonItem)
}
@objc func toggleReaderView(_ sender: Any?) {
currentWebViewController?.toggleArticleExtractor()
}
// MARK: Keyboard Shortcuts
@objc func navigateToTimeline(_ sender: Any?) {
coordinator.navigateToTimeline()
}
// MARK: API
func focus() {
currentWebViewController?.focus()
}
func canScrollDown() -> Bool {
return currentWebViewController?.canScrollDown() ?? false
}
func canScrollUp() -> Bool {
return currentWebViewController?.canScrollUp() ?? false
}
func scrollPageDown() {
currentWebViewController?.scrollPageDown()
}
func scrollPageUp() {
currentWebViewController?.scrollPageUp()
}
func stopArticleExtractorIfProcessing() {
currentWebViewController?.stopArticleExtractorIfProcessing()
}
func openInAppBrowser() {
currentWebViewController?.openInAppBrowser()
}
func setScrollPosition(isShowingExtractedArticle: Bool, articleWindowScrollY: Int) {
currentWebViewController?.setScrollPosition(isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY)
}
}
// MARK: Find in Article
public extension Notification.Name {
static let FindInArticle = Notification.Name("FindInArticle")
static let EndFindInArticle = Notification.Name("EndFindInArticle")
}
extension ArticleViewController: SearchBarDelegate {
func searchBar(_ searchBar: ArticleSearchBar, textDidChange searchText: String) {
currentWebViewController?.searchText(searchText) {
found in
searchBar.resultsCount = found.count
if let index = found.index {
searchBar.selectedResult = index + 1
}
}
}
func doneWasPressed(_ searchBar: ArticleSearchBar) {
NotificationCenter.default.post(name: .EndFindInArticle, object: nil)
}
func nextWasPressed(_ searchBar: ArticleSearchBar) {
if searchBar.selectedResult < searchBar.resultsCount {
currentWebViewController?.selectNextSearchResult()
searchBar.selectedResult += 1
}
}
func previousWasPressed(_ searchBar: ArticleSearchBar) {
if searchBar.selectedResult > 1 {
currentWebViewController?.selectPreviousSearchResult()
searchBar.selectedResult -= 1
}
}
}
extension ArticleViewController {
@objc func beginFind(_ _: Any? = nil) {
searchBar.isHidden = false
navigationController?.setToolbarHidden(true, animated: true)
currentWebViewController?.additionalSafeAreaInsets.bottom = searchBar.frame.height
searchBar.becomeFirstResponder()
}
@objc func endFind(_ _: Any? = nil) {
searchBar.resignFirstResponder()
searchBar.isHidden = true
navigationController?.setToolbarHidden(false, animated: true)
currentWebViewController?.additionalSafeAreaInsets.bottom = 0
currentWebViewController?.endSearch()
}
@objc func keyboardWillChangeFrame(_ notification: Notification) {
if !searchBar.isHidden,
let duration = notification.userInfo?[UIWindow.keyboardAnimationDurationUserInfoKey] as? Double,
let curveRaw = notification.userInfo?[UIWindow.keyboardAnimationCurveUserInfoKey] as? UInt,
let frame = notification.userInfo?[UIWindow.keyboardFrameEndUserInfoKey] as? CGRect {
let curve = UIView.AnimationOptions(rawValue: curveRaw)
let newHeight = view.safeAreaLayoutGuide.layoutFrame.maxY - frame.minY
currentWebViewController?.additionalSafeAreaInsets.bottom = newHeight + searchBar.frame.height + 10
self.searchBarBottomConstraint.constant = newHeight
UIView.animate(withDuration: duration, delay: 0, options: curve, animations: {
self.view.layoutIfNeeded()
})
}
}
}
// MARK: WebViewControllerDelegate
extension ArticleViewController: WebViewControllerDelegate {
func webViewController(_ webViewController: WebViewController, articleExtractorButtonStateDidUpdate buttonState: ArticleExtractorButtonState) {
if webViewController === currentWebViewController {
articleExtractorButton.buttonState = buttonState
}
}
}
// MARK: UIPageViewControllerDataSource
extension ArticleViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let webViewController = viewController as? WebViewController,
let currentArticle = webViewController.article,
let article = coordinator.findPrevArticle(currentArticle) else {
return nil
}
return createWebViewController(article)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let webViewController = viewController as? WebViewController,
let currentArticle = webViewController.article,
let article = coordinator.findNextArticle(currentArticle) else {
return nil
}
return createWebViewController(article)
}
}
// MARK: UIPageViewControllerDelegate
extension ArticleViewController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
guard finished, completed else { return }
guard let article = currentWebViewController?.article else { return }
coordinator.selectArticle(article, animations: [.select, .scroll, .navigation])
articleExtractorButton.buttonState = currentWebViewController?.articleExtractorButtonState ?? .off
previousViewControllers.compactMap({ $0 as? WebViewController }).forEach({ $0.stopWebViewActivity() })
}
}
// MARK: UIGestureRecognizerDelegate
extension ArticleViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
let point = gestureRecognizer.location(in: nil)
if point.x > 40 {
return true
}
return false
}
}
// MARK: Private
private extension ArticleViewController {
func createWebViewController(_ article: Article?, updateView: Bool = true) -> WebViewController {
let controller = WebViewController()
controller.coordinator = coordinator
controller.delegate = self
controller.setArticle(article, updateView: updateView)
return controller
}
}
|
c2aa2dad3aefa76e5086538f0ea1e1bf
| 33.756646 | 187 | 0.783655 | false | false | false | false |
AnarchyTools/atbuild
|
refs/heads/master
|
attools/src/CustomTool.swift
|
apache-2.0
|
1
|
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import atpkg
///Create a tool out of another program someone has lying around on their system
///Important: this is for programs that are written for AT. For other programs, use shell instead.
final class CustomTool: Tool {
static func isCustomTool(name: String) -> Bool {
return name.hasSuffix(".attool")
}
let name: String
init(name: String) {
self.name = String(name.characters[name.characters.startIndex..<name.characters.index(name.characters.startIndex, offsetBy: name.characters.count - 7)])
}
func run(task: Task) {
var cmd = "\(self.name) "
for key in task.allKeys.sorted() {
if Task.Option.allOptions.map({$0.rawValue}).contains(key) { continue }
guard let value = task[key]?.string else {
fatalError("\(task.qualifiedName).\(key) is not string")
}
cmd += "--\(key) \"\(evaluateSubstitutions(input: value, package: task.package))\" "
}
let env = Shell.environment(task: task)
anarchySystem(cmd,additionalEnvironment: env)
}
}
|
51b5223d7a3f03ec6f78331502727bd7
| 37 | 160 | 0.640351 | false | false | false | false |
OpenMindBR/swift-diversidade-app
|
refs/heads/master
|
Diversidade/DiscoveringViewController.swift
|
mit
|
1
|
//
// DiscoveringViewController.swift
// Diversidade
//
// Created by Francisco José A. C. Souza on 24/02/16.
// Copyright © 2016 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class DiscoveringViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var postsTableView: UITableView!
@IBOutlet weak var menuItem: UIBarButtonItem!
@IBOutlet weak var loadingPostsIndicator: UIActivityIndicatorView!
var datasource:[Post]?
override func viewDidLoad() {
datasource = []
super.viewDidLoad()
self.configureSideMenu(self.menuItem)
self.retrieveDiscoveringPosts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
if let datasource = self.datasource {
rows = datasource.count
}
return rows
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("discovering_cell", forIndexPath: indexPath) as! PostTableViewCell
if let datasource = self.datasource {
let content = datasource[indexPath.row]
cell.titleLabel.text = content.title
cell.postTextLabel.text = content.text
}
return cell
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 500.0
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let datasource = datasource, let sourceUrl = datasource[indexPath.row].url {
if let url = NSURL(string: sourceUrl) {
UIApplication.sharedApplication().openURL(url)
}
}
}
func retrieveDiscoveringPosts() {
let requestString = UrlFormatter.urlForNewsFromCategory(Category.Discovering)
Alamofire.request(.GET, requestString).validate().responseJSON { (response) in
switch response.result {
case .Success:
if let value = response.result.value {
let json: Array<JSON> = JSON(value).arrayValue
let posts: [Post] = json.map({ (post) -> Post in
let text = post["text"].stringValue
let title = post["title"].stringValue
let url = post["source"].stringValue
return Post(title: title, url: url, text: text)
})
self.datasource = posts
self.loadingPostsIndicator.stopAnimating()
self.postsTableView.reloadData()
}
case .Failure:
print (response.result.error)
}
}
}
}
|
9743c06fe0805cecb0c93964c3cb9046
| 31.798165 | 129 | 0.587133 | false | false | false | false |
touchopia/HackingWithSwift
|
refs/heads/master
|
project23/Project23/GameScene.swift
|
unlicense
|
1
|
//
// GameScene.swift
// Project23
//
// Created by TwoStraws on 19/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import GameplayKit
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var starfield: SKEmitterNode!
var player: SKSpriteNode!
var scoreLabel: SKLabelNode!
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var possibleEnemies = ["ball", "hammer", "tv"]
var gameTimer: Timer!
var isGameOver = false
override func didMove(to view: SKView) {
backgroundColor = UIColor.black
starfield = SKEmitterNode(fileNamed: "Starfield")!
starfield.position = CGPoint(x: 1024, y: 384)
starfield.advanceSimulationTime(10)
addChild(starfield)
starfield.zPosition = -1
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 100, y: 384)
player.physicsBody = SKPhysicsBody(texture: player.texture!, size: player.size)
player.physicsBody!.contactTestBitMask = 1
addChild(player)
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.position = CGPoint(x: 16, y: 16)
scoreLabel.horizontalAlignmentMode = .left
addChild(scoreLabel)
score = 0
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
gameTimer = Timer.scheduledTimer(timeInterval: 0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)
}
func createEnemy() {
possibleEnemies = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possibleEnemies) as! [String]
let randomDistribution = GKRandomDistribution(lowestValue: 50, highestValue: 736)
let sprite = SKSpriteNode(imageNamed: possibleEnemies[0])
sprite.position = CGPoint(x: 1200, y: randomDistribution.nextInt())
addChild(sprite)
sprite.physicsBody = SKPhysicsBody(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.categoryBitMask = 1
sprite.physicsBody?.velocity = CGVector(dx: -500, dy: 0)
sprite.physicsBody?.angularVelocity = 5
sprite.physicsBody?.linearDamping = 0
sprite.physicsBody?.angularDamping = 0
}
override func update(_ currentTime: TimeInterval) {
for node in children {
if node.position.x < -300 {
node.removeFromParent()
}
}
if !isGameOver {
score += 1
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
var location = touch.location(in: self)
if location.y < 100 {
location.y = 100
} else if location.y > 668 {
location.y = 668
}
player.position = location
}
func didBegin(_ contact: SKPhysicsContact) {
let explosion = SKEmitterNode(fileNamed: "explosion")!
explosion.position = player.position
addChild(explosion)
player.removeFromParent()
isGameOver = true
}
}
|
e14ded37792dee386052f8b29cdc5369
| 25.542857 | 132 | 0.723358 | false | false | false | false |
longitachi/ZLPhotoBrowser
|
refs/heads/master
|
Sources/Edit/ZLImageStickerView.swift
|
mit
|
1
|
//
// ZLImageStickerView.swift
// ZLPhotoBrowser
//
// Created by long on 2020/11/20.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// 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
protocol ZLStickerViewDelegate: NSObject {
// Called when scale or rotate or move.
func stickerBeginOperation(_ sticker: UIView)
// Called during scale or rotate or move.
func stickerOnOperation(_ sticker: UIView, panGes: UIPanGestureRecognizer)
// Called after scale or rotate or move.
func stickerEndOperation(_ sticker: UIView, panGes: UIPanGestureRecognizer)
// Called when tap sticker.
func stickerDidTap(_ sticker: UIView)
}
protocol ZLStickerViewAdditional: NSObject {
var gesIsEnabled: Bool { get set }
func resetState()
func moveToAshbin()
func addScale(_ scale: CGFloat)
}
class ZLImageStickerView: UIView, ZLStickerViewAdditional {
private static let edgeInset: CGFloat = 20
private static let borderWidth = 1 / UIScreen.main.scale
private var firstLayout = true
private let originScale: CGFloat
private let originAngle: CGFloat
private var originTransform: CGAffineTransform = .identity
private let image: UIImage
private var timer: Timer?
private lazy var imageView: UIImageView = {
let view = UIImageView(image: image)
view.contentMode = .scaleAspectFit
view.clipsToBounds = true
return view
}()
private var totalTranslationPoint: CGPoint = .zero
private var gesTranslationPoint: CGPoint = .zero
private var gesRotation: CGFloat = 0
private var gesScale: CGFloat = 1
private var onOperation = false
private lazy var tapGes = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
lazy var pinchGes: UIPinchGestureRecognizer = {
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinchAction(_:)))
pinch.delegate = self
return pinch
}()
lazy var panGes: UIPanGestureRecognizer = {
let pan = UIPanGestureRecognizer(target: self, action: #selector(panAction(_:)))
pan.delegate = self
return pan
}()
var gesIsEnabled = true
var originFrame: CGRect
weak var delegate: ZLStickerViewDelegate?
// Conver all states to model.
var state: ZLImageStickerState {
return ZLImageStickerState(
image: image,
originScale: originScale,
originAngle: originAngle,
originFrame: originFrame,
gesScale: gesScale,
gesRotation: gesRotation,
totalTranslationPoint: totalTranslationPoint
)
}
deinit {
zl_debugPrint("ZLImageStickerView deinit")
cleanTimer()
}
convenience init(from state: ZLImageStickerState) {
self.init(
image: state.image,
originScale: state.originScale,
originAngle: state.originAngle,
originFrame: state.originFrame,
gesScale: state.gesScale,
gesRotation: state.gesRotation,
totalTranslationPoint: state.totalTranslationPoint,
showBorder: false
)
}
init(
image: UIImage,
originScale: CGFloat,
originAngle: CGFloat,
originFrame: CGRect,
gesScale: CGFloat = 1,
gesRotation: CGFloat = 0,
totalTranslationPoint: CGPoint = .zero,
showBorder: Bool = true
) {
self.image = image
self.originScale = originScale
self.originAngle = originAngle
self.originFrame = originFrame
super.init(frame: .zero)
self.gesScale = gesScale
self.gesRotation = gesRotation
self.totalTranslationPoint = totalTranslationPoint
layer.borderWidth = ZLTextStickerView.borderWidth
hideBorder()
if showBorder {
startTimer()
}
addSubview(imageView)
addGestureRecognizer(tapGes)
addGestureRecognizer(pinchGes)
let rotationGes = UIRotationGestureRecognizer(target: self, action: #selector(rotationAction(_:)))
rotationGes.delegate = self
addGestureRecognizer(rotationGes)
addGestureRecognizer(panGes)
tapGes.require(toFail: panGes)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard firstLayout else { return }
// Rotate must be first when first layout.
transform = transform.rotated(by: originAngle.zl.toPi)
if totalTranslationPoint != .zero {
if originAngle == 90 {
transform = transform.translatedBy(x: totalTranslationPoint.y, y: -totalTranslationPoint.x)
} else if originAngle == 180 {
transform = transform.translatedBy(x: -totalTranslationPoint.x, y: -totalTranslationPoint.y)
} else if originAngle == 270 {
transform = transform.translatedBy(x: -totalTranslationPoint.y, y: totalTranslationPoint.x)
} else {
transform = transform.translatedBy(x: totalTranslationPoint.x, y: totalTranslationPoint.y)
}
}
transform = transform.scaledBy(x: originScale, y: originScale)
originTransform = transform
if gesScale != 1 {
transform = transform.scaledBy(x: gesScale, y: gesScale)
}
if gesRotation != 0 {
transform = transform.rotated(by: gesRotation)
}
firstLayout = false
imageView.frame = bounds.insetBy(dx: ZLImageStickerView.edgeInset, dy: ZLImageStickerView.edgeInset)
}
@objc private func tapAction(_ ges: UITapGestureRecognizer) {
guard gesIsEnabled else { return }
superview?.bringSubviewToFront(self)
delegate?.stickerDidTap(self)
startTimer()
}
@objc private func pinchAction(_ ges: UIPinchGestureRecognizer) {
guard gesIsEnabled else { return }
gesScale *= ges.scale
ges.scale = 1
if ges.state == .began {
setOperation(true)
} else if ges.state == .changed {
updateTransform()
} else if ges.state == .ended || ges.state == .cancelled {
setOperation(false)
}
}
@objc private func rotationAction(_ ges: UIRotationGestureRecognizer) {
guard gesIsEnabled else { return }
gesRotation += ges.rotation
ges.rotation = 0
if ges.state == .began {
setOperation(true)
} else if ges.state == .changed {
updateTransform()
} else if ges.state == .ended || ges.state == .cancelled {
setOperation(false)
}
}
@objc private func panAction(_ ges: UIPanGestureRecognizer) {
guard gesIsEnabled else { return }
let point = ges.translation(in: superview)
gesTranslationPoint = CGPoint(x: point.x / originScale, y: point.y / originScale)
if ges.state == .began {
setOperation(true)
} else if ges.state == .changed {
updateTransform()
} else if ges.state == .ended || ges.state == .cancelled {
totalTranslationPoint.x += point.x
totalTranslationPoint.y += point.y
setOperation(false)
if originAngle == 90 {
originTransform = originTransform.translatedBy(x: gesTranslationPoint.y, y: -gesTranslationPoint.x)
} else if originAngle == 180 {
originTransform = originTransform.translatedBy(x: -gesTranslationPoint.x, y: -gesTranslationPoint.y)
} else if originAngle == 270 {
originTransform = originTransform.translatedBy(x: -gesTranslationPoint.y, y: gesTranslationPoint.x)
} else {
originTransform = originTransform.translatedBy(x: gesTranslationPoint.x, y: gesTranslationPoint.y)
}
gesTranslationPoint = .zero
}
}
private func setOperation(_ isOn: Bool) {
if isOn, !onOperation {
onOperation = true
cleanTimer()
layer.borderColor = UIColor.white.cgColor
superview?.bringSubviewToFront(self)
delegate?.stickerBeginOperation(self)
} else if !isOn, onOperation {
onOperation = false
startTimer()
delegate?.stickerEndOperation(self, panGes: panGes)
}
}
private func updateTransform() {
var transform = originTransform
if originAngle == 90 {
transform = transform.translatedBy(x: gesTranslationPoint.y, y: -gesTranslationPoint.x)
} else if originAngle == 180 {
transform = transform.translatedBy(x: -gesTranslationPoint.x, y: -gesTranslationPoint.y)
} else if originAngle == 270 {
transform = transform.translatedBy(x: -gesTranslationPoint.y, y: gesTranslationPoint.x)
} else {
transform = transform.translatedBy(x: gesTranslationPoint.x, y: gesTranslationPoint.y)
}
// Scale must after translate.
transform = transform.scaledBy(x: gesScale, y: gesScale)
// Rotate must after scale.
transform = transform.rotated(by: gesRotation)
self.transform = transform
delegate?.stickerOnOperation(self, panGes: panGes)
}
@objc private func hideBorder() {
layer.borderColor = UIColor.clear.cgColor
}
private func startTimer() {
cleanTimer()
layer.borderColor = UIColor.white.cgColor
timer = Timer.scheduledTimer(timeInterval: 2, target: ZLWeakProxy(target: self), selector: #selector(hideBorder), userInfo: nil, repeats: false)
RunLoop.current.add(timer!, forMode: .default)
}
private func cleanTimer() {
timer?.invalidate()
timer = nil
}
func resetState() {
onOperation = false
cleanTimer()
hideBorder()
}
func moveToAshbin() {
cleanTimer()
removeFromSuperview()
}
func addScale(_ scale: CGFloat) {
// Revert zoom scale.
transform = transform.scaledBy(x: 1 / originScale, y: 1 / originScale)
// Revert ges scale.
transform = transform.scaledBy(x: 1 / gesScale, y: 1 / gesScale)
// Revert ges rotation.
transform = transform.rotated(by: -gesRotation)
var origin = frame.origin
origin.x *= scale
origin.y *= scale
let newSize = CGSize(width: frame.width * scale, height: frame.height * scale)
let newOrigin = CGPoint(x: frame.minX + (frame.width - newSize.width) / 2, y: frame.minY + (frame.height - newSize.height) / 2)
let diffX: CGFloat = (origin.x - newOrigin.x)
let diffY: CGFloat = (origin.y - newOrigin.y)
if originAngle == 90 {
transform = transform.translatedBy(x: diffY, y: -diffX)
originTransform = originTransform.translatedBy(x: diffY / originScale, y: -diffX / originScale)
} else if originAngle == 180 {
transform = transform.translatedBy(x: -diffX, y: -diffY)
originTransform = originTransform.translatedBy(x: -diffX / originScale, y: -diffY / originScale)
} else if originAngle == 270 {
transform = transform.translatedBy(x: -diffY, y: diffX)
originTransform = originTransform.translatedBy(x: -diffY / originScale, y: diffX / originScale)
} else {
transform = transform.translatedBy(x: diffX, y: diffY)
originTransform = originTransform.translatedBy(x: diffX / originScale, y: diffY / originScale)
}
totalTranslationPoint.x += diffX
totalTranslationPoint.y += diffY
transform = transform.scaledBy(x: scale, y: scale)
// Readd zoom scale.
transform = transform.scaledBy(x: originScale, y: originScale)
// Readd ges scale.
transform = transform.scaledBy(x: gesScale, y: gesScale)
// Readd ges rotation.
transform = transform.rotated(by: gesRotation)
gesScale *= scale
}
class func calculateSize(image: UIImage, width: CGFloat) -> CGSize {
let maxSide = width / 2
let minSide: CGFloat = 100
let whRatio = image.size.width / image.size.height
var size: CGSize = .zero
if whRatio >= 1 {
let w = min(maxSide, max(minSide, image.size.width))
let h = w / whRatio
size = CGSize(width: w, height: h)
} else {
let h = min(maxSide, max(minSide, image.size.width))
let w = h * whRatio
size = CGSize(width: w, height: h)
}
size.width += ZLImageStickerView.edgeInset * 2
size.height += ZLImageStickerView.edgeInset * 2
return size
}
}
extension ZLImageStickerView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
public class ZLImageStickerState: NSObject {
let image: UIImage
let originScale: CGFloat
let originAngle: CGFloat
let originFrame: CGRect
let gesScale: CGFloat
let gesRotation: CGFloat
let totalTranslationPoint: CGPoint
init(
image: UIImage,
originScale: CGFloat,
originAngle: CGFloat,
originFrame: CGRect,
gesScale: CGFloat,
gesRotation: CGFloat,
totalTranslationPoint: CGPoint
) {
self.image = image
self.originScale = originScale
self.originAngle = originAngle
self.originFrame = originFrame
self.gesScale = gesScale
self.gesRotation = gesRotation
self.totalTranslationPoint = totalTranslationPoint
super.init()
}
}
|
9b735ed81dd8960cd294249e0c04e63e
| 33.848416 | 157 | 0.618256 | false | false | false | false |
MakeSchool/TripPlanner
|
refs/heads/master
|
TripPlanner/UI/MainScene/MainViewController.swift
|
mit
|
1
|
//
// MainViewController.swift
// TripPlanner
//
// Created by Benjamin Encz on 7/21/15.
// Copyright © 2015 Make School. All rights reserved.
//
import Foundation
import ListKit
import CoreData
class MainViewController: UIViewController {
@IBOutlet var tableView: UITableView!
var coreDataClient: CoreDataClient!
var currentTrip: Trip?
var detailViewTrip: Trip?
var temporaryContext: NSManagedObjectContext?
private var arrayDataSource: ArrayDataSource<TripMainTableViewCell, Trip>!
var trips: [Trip]? {
didSet {
if let trips = trips {
let nib = UINib(nibName: "TripMainTableViewCell", bundle: NSBundle.mainBundle())
arrayDataSource = ArrayDataSource(array: trips, cellType: TripMainTableViewCell.self, nib: nib)
self.tableView.reloadData()
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
trips = coreDataClient.allTrips()
self.tableView.dataSource = self
}
// MARK: Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "AddNewTrip") {
let (newTrip, newContext) = coreDataClient.createObjectInTemporaryContext(Trip.self)
currentTrip = newTrip
temporaryContext = newContext
let addTripViewController = segue.destinationViewController as? AddTripViewController
if let addTripViewController = addTripViewController {
addTripViewController.currentTrip = currentTrip
}
} else if (segue.identifier == "ShowTripDetails") {
let tripDetailViewController = segue.destinationViewController as? TripDetailViewController
if let tripDetailViewController = tripDetailViewController {
prepareTripDetailPresentation(tripDetailViewController)
}
}
}
func prepareTripDetailPresentation(tripDetailVC: TripDetailViewController) {
tripDetailVC.trip = detailViewTrip
tripDetailVC.coreDataClient = coreDataClient
}
// MARK: Unwind Segues
@IBAction func saveTrip(segue:UIStoryboardSegue) {
if (segue.identifier == Storyboard.UnwindSegues.ExitSaveTripSegue) {
try! temporaryContext?.save()
coreDataClient.saveStack()
}
}
@IBAction func cancelTripCreation(segue:UIStoryboardSegue) {
if (segue.identifier == Storyboard.UnwindSegues.ExitCancelTripSegue) {
temporaryContext = nil
}
}
// MARK: Button Callbacks
@IBAction func refreshButtonTapped(sender: AnyObject) {
let tripPlannerBackendSynchronizer = TripPlannerBackendSynchronizer(coreDataClient: coreDataClient)
tripPlannerBackendSynchronizer.sync {
self.trips = self.coreDataClient.allTrips()
self.tableView.reloadData()
}
}
}
extension MainViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard let trips = trips else { return }
detailViewTrip = trips[indexPath.row]
performSegueWithIdentifier("ShowTripDetails", sender: self)
}
}
extension MainViewController: UITableViewDataSource {
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == .Delete) {
let tripToDelete = arrayDataSource.array[indexPath.row]
arrayDataSource.array.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
coreDataClient.markTripAsDeleted(tripToDelete)
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return arrayDataSource.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayDataSource.tableView(tableView, numberOfRowsInSection: section)
}
}
|
20cb55928525923e2f90c5ef9cecf5de
| 31.04878 | 146 | 0.738899 | false | false | false | false |
OscarSwanros/swift
|
refs/heads/master
|
stdlib/public/SDK/XCTest/XCTest.swift
|
apache-2.0
|
3
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import XCTest // Clang module
import CoreGraphics
import _SwiftXCTestOverlayShims
// --- XCTest API Swiftification ---
public extension XCTContext {
/// Create and run a new activity with provided name and block.
public class func runActivity<Result>(named name: String, block: (XCTActivity) throws -> Result) rethrows -> Result {
let context = _XCTContextCurrent()
if _XCTContextShouldStartActivity(context, XCTActivityTypeUserCreated) {
return try autoreleasepool {
let activity = _XCTContextWillStartActivity(context, name, XCTActivityTypeUserCreated)
defer {
_XCTContextDidFinishActivity(context, activity)
}
return try block(activity)
}
} else {
fatalError("XCTContext.runActivity(named:block:) failed because activities are disallowed in the current configuration.")
}
}
}
#if os(macOS)
@available(swift 4.0)
@available(macOS 10.11, *)
public extension XCUIElement {
/// Types a single key from the XCUIKeyboardKey enumeration with the specified modifier flags.
@nonobjc public func typeKey(_ key: XCUIKeyboardKey, modifierFlags: XCUIKeyModifierFlags) {
// Call the version of the method defined in XCTest.framework.
typeKey(key.rawValue, modifierFlags: modifierFlags)
}
}
#endif
// --- Failure Formatting ---
/// Register the failure, expected or unexpected, of the current test case.
func _XCTRegisterFailure(_ expected: Bool, _ condition: String, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) {
// Call the real _XCTFailureHandler.
let test = _XCTCurrentTestCase()
_XCTPreformattedFailureHandler(test, expected, file.description, line, condition, message())
}
/// Produce a failure description for the given assertion type.
func _XCTFailureDescription(_ assertionType: _XCTAssertionType, _ formatIndex: UInt, _ expressionStrings: CVarArg...) -> String {
// In order to avoid revlock/submission issues between XCTest and the Swift XCTest overlay,
// we are using the convention with _XCTFailureFormat that (formatIndex >= 100) should be
// treated just like (formatIndex - 100), but WITHOUT the expression strings. (Swift can't
// stringify the expressions, only their values.) This way we don't have to introduce a new
// BOOL parameter to this semi-internal function and coordinate that across builds.
//
// Since there's a single bottleneck in the overlay where we invoke _XCTFailureFormat, just
// add the formatIndex adjustment there rather than in all of the individual calls to this
// function.
return String(format: _XCTFailureFormat(assertionType, formatIndex + 100), arguments: expressionStrings)
}
// --- Exception Support ---
/// The Swift-style result of evaluating a block which may throw an exception.
enum _XCTThrowableBlockResult {
case success
case failedWithError(error: Error)
case failedWithException(className: String, name: String, reason: String)
case failedWithUnknownException
}
/// Asks some Objective-C code to evaluate a block which may throw an exception or error,
/// and if it does consume the exception and return information about it.
func _XCTRunThrowableBlock(_ block: () throws -> Void) -> _XCTThrowableBlockResult {
var blockErrorOptional: Error?
let exceptionResult = _XCTRunThrowableBlockBridge({
do {
try block()
} catch {
blockErrorOptional = error
}
})
if let blockError = blockErrorOptional {
return .failedWithError(error: blockError)
} else if let exceptionResult = exceptionResult {
if exceptionResult["type"] == "objc" {
return .failedWithException(
className: exceptionResult["className"]!,
name: exceptionResult["name"]!,
reason: exceptionResult["reason"]!)
} else {
return .failedWithUnknownException
}
} else {
return .success
}
}
// --- Supported Assertions ---
public func XCTFail(_ message: String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.fail
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, "" as NSString), message, file, line)
}
public func XCTAssertNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`nil`
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = false
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = true
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotNil(_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notNil
// evaluate the expression exactly once
var expressionValueOptional: Any?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
// test both Optional and value to treat .none and nil as synonymous
var passed: Bool
var expressionValueStr: String = "nil"
if let expressionValueUnwrapped = expressionValueOptional {
passed = true
expressionValueStr = "\(expressionValueUnwrapped)"
} else {
passed = false
}
if !passed {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotNil failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssert(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
// XCTAssert is just a cover for XCTAssertTrue.
XCTAssertTrue(expression, message, file: file, line: line)
}
public func XCTAssertTrue(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`true`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if !expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertTrue failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertFalse(_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.`false`
// evaluate the expression exactly once
var expressionValueOptional: Bool?
let result = _XCTRunThrowableBlock {
expressionValueOptional = try expression()
}
switch result {
case .success:
let expressionValue = expressionValueOptional!
if expressionValue {
// TODO: @auto_string expression
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertFalse failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME(ABI): once <rdar://problem/17144340> is implemented, this could be
// changed to take two T rather than two T? since Optional<Equatable>: Equatable
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
// FIXME: remove optionality once this is generic over Equatable T
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional != expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
// once this function is generic over T, it will only print these
// values as optional when they are...
let expressionValueStr1 = String(describing: expressionValue1Optional)
let expressionValueStr2 = String(describing: expressionValue2Optional)
// FIXME: this file seems to use `as NSString` unnecessarily a lot,
// unless I'm missing something.
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME(ABI): Due to <rdar://problem/17144340> we need overrides of
// XCTAssertEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equal
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 != expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: T = expressionValue1Optional!
let expressionValue2: T = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
if expressionValue1Optional == expressionValue2Optional {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = String(describing: expressionValue1Optional)
let expressionValueStr2 = String(describing: expressionValue2Optional)
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
// FIXME: Due to <rdar://problem/16768059> we need overrides of XCTAssertNotEqual for:
// ContiguousArray<T>
// ArraySlice<T>
// Array<T>
// Dictionary<T, U>
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ContiguousArray<T>, _ expression2: @autoclosure () throws -> ContiguousArray<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ContiguousArray<T>?
var expressionValue2Optional: ContiguousArray<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ContiguousArray<T> = expressionValue1Optional!
let expressionValue2: ContiguousArray<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> ArraySlice<T>, _ expression2: @autoclosure () throws -> ArraySlice<T>, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: ArraySlice<T>?
var expressionValue2Optional: ArraySlice<T>?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: ArraySlice<T> = expressionValue1Optional!
let expressionValue2: ArraySlice<T> = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T : Equatable>(_ expression1: @autoclosure () throws -> [T], _ expression2: @autoclosure () throws -> [T], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T]?
var expressionValue2Optional: [T]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T] = expressionValue1Optional!
let expressionValue2: [T] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertNotEqual<T, U : Equatable>(_ expression1: @autoclosure () throws -> [T: U], _ expression2: @autoclosure () throws -> [T: U], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqual
// evaluate each expression exactly once
var expressionValue1Optional: [T: U]?
var expressionValue2Optional: [T: U]?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1: [T: U] = expressionValue1Optional!
let expressionValue2: [T: U] = expressionValue2Optional!
if expressionValue1 == expressionValue2 {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
func _XCTCheckEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
func _XCTCheckEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (!value1.isNaN && !value2.isNaN)
&& (abs(value1 - value2) <= accuracy)
}
public func XCTAssertEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.equalWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var equalWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
equalWithAccuracy = _XCTCheckEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("Unsupported floating-point type passed to XCTAssertEqual")
}
if !equalWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
@available(*, deprecated, renamed: "XCTAssertEqual(_:_:accuracy:file:line:)")
public func XCTAssertEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(expression1, expression2, accuracy: accuracy, message, file: file, line: line)
}
func _XCTCheckNotEqualWithAccuracy_Double(_ value1: Double, _ value2: Double, _ accuracy: Double) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_Float(_ value1: Float, _ value2: Float, _ accuracy: Float) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
func _XCTCheckNotEqualWithAccuracy_CGFloat(_ value1: CGFloat, _ value2: CGFloat, _ accuracy: CGFloat) -> Bool {
return (value1.isNaN || value2.isNaN)
|| (abs(value1 - value2) > accuracy)
}
public func XCTAssertNotEqual<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.notEqualWithAccuracy
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
var notEqualWithAccuracy: Bool = false
switch (expressionValue1, expressionValue2, accuracy) {
case let (expressionValue1Double as Double, expressionValue2Double as Double, accuracyDouble as Double):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Double(expressionValue1Double, expressionValue2Double, accuracyDouble)
case let (expressionValue1Float as Float, expressionValue2Float as Float, accuracyFloat as Float):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_Float(expressionValue1Float, expressionValue2Float, accuracyFloat)
case let (expressionValue1CGFloat as CGFloat, expressionValue2CGFloat as CGFloat, accuracyCGFloat as CGFloat):
notEqualWithAccuracy = _XCTCheckNotEqualWithAccuracy_CGFloat(expressionValue1CGFloat, expressionValue2CGFloat, accuracyCGFloat)
default:
// unknown type, fail with prejudice
_preconditionFailure("Unsupported floating-point type passed to XCTAssertNotEqual")
}
if !notEqualWithAccuracy {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
let accuracyStr = "\(accuracy)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString, accuracyStr as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertNotEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
@available(*, deprecated, renamed: "XCTAssertNotEqual(_:_:accuracy:file:line:)")
public func XCTAssertNotEqualWithAccuracy<T : FloatingPoint>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ accuracy: T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
XCTAssertNotEqual(expression1, expression2, accuracy: accuracy, message, file: file, line: line)
}
public func XCTAssertGreaterThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.greaterThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 > expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertGreaterThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.greaterThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 >= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertGreaterThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThan<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.lessThan
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 < expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThan failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertLessThanOrEqual<T : Comparable>(_ expression1: @autoclosure () throws -> T, _ expression2: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line)
{
let assertionType = _XCTAssertionType.lessThanOrEqual
// evaluate each expression exactly once
var expressionValue1Optional: T?
var expressionValue2Optional: T?
let result = _XCTRunThrowableBlock {
expressionValue1Optional = try expression1()
expressionValue2Optional = try expression2()
}
switch result {
case .success:
let expressionValue1 = expressionValue1Optional!
let expressionValue2 = expressionValue2Optional!
if !(expressionValue1 <= expressionValue2) {
// TODO: @auto_string expression1
// TODO: @auto_string expression2
let expressionValueStr1 = "\(expressionValue1)"
let expressionValueStr2 = "\(expressionValue2)"
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 0, expressionValueStr1 as NSString, expressionValueStr2 as NSString), message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertLessThanOrEqual failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(false, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
public func XCTAssertThrowsError<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line, _ errorHandler: (_ error: Error) -> Void = { _ in }) {
// evaluate expression exactly once
var caughtErrorOptional: Error?
let result = _XCTRunThrowableBlock {
do {
_ = try expression()
} catch {
caughtErrorOptional = error
}
}
switch result {
case .success:
if let caughtError = caughtErrorOptional {
errorHandler(caughtError)
} else {
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: did not throw an error", message, file, line)
}
case .failedWithError(let error):
_XCTRegisterFailure(false, "XCTAssertThrowsError failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing \(reason)", message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, "XCTAssertThrowsError failed: throwing an unknown exception", message, file, line)
}
}
public func XCTAssertNoThrow<T>(_ expression: @autoclosure () throws -> T, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.noThrow
let result = _XCTRunThrowableBlock { _ = try expression() }
switch result {
case .success:
return
case .failedWithError(let error):
_XCTRegisterFailure(true, "XCTAssertNoThrow failed: threw error \"\(error)\"", message, file, line)
case .failedWithException(_, _, let reason):
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 1, reason as NSString), message, file, line)
case .failedWithUnknownException:
_XCTRegisterFailure(true, _XCTFailureDescription(assertionType, 2), message, file, line)
}
}
#if XCTEST_ENABLE_EXCEPTION_ASSERTIONS
// --- Currently-Unsupported Assertions ---
public func XCTAssertThrows(_ expression: @autoclosure () -> Any?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_Throws
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecific
// FIXME: Unsupported
}
public func XCTAssertThrowsSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_ThrowsSpecificNamed
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecific(_ expression: @autoclosure () -> Any?, _ exception: Any, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecific
// FIXME: Unsupported
}
public func XCTAssertNoThrowSpecificNamed(_ expression: @autoclosure () -> Any?, _ exception: Any, _ name: String, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) {
let assertionType = _XCTAssertionType.assertion_NoThrowSpecificNamed
// FIXME: Unsupported
}
#endif
|
731c98e90dee0a179e8bfc6946ae521d
| 40.481383 | 259 | 0.709324 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.